import {
    API_SERVER
} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_SHOP_PACKAGES,
    RECIEVE_SHOP_PACKAGES,
    REQUEST_SHOP_COMMERCIAL_LEADS,
    RECIEVE_SHOP_COMMERCIAL_LEADS,
    SELECT_SHOP_COMMERCIAL_LEAD
} from '../../constants/coMarketConstants';
import { fromWCPackage } from '../../helpers/PackageHelper';

const client = new HtmlClient();

const requestShopPackages = () => ({
    type: REQUEST_SHOP_PACKAGES,
    isLoading: true
});
const recieveShopPackages = (json) => ({
    type: RECIEVE_SHOP_PACKAGES,
    isLoading: false,
    shopPackages: json
});

export const fetchShopPackages = (cl, search) => {
    return dispatch => {
        dispatch(requestShopPackages());
        let searchParam = search ?  '?search=' +search : ''

        return client.fetch({
            url: `${API_SERVER}/wp-json/wc/v2/products?cl_id=${cl.idCommercialLead}` + searchParam,
        })
            .then(response => {
                if (response.data) {
                    dispatch(recieveShopPackages(response.data.map(wcPackage => fromWCPackage(wcPackage))))
                }
            })
            .catch(error => {
                client.onError(error, dispatch);
            });
    }
}

const requestShopCommercialLeads = () => ({
    type: REQUEST_SHOP_COMMERCIAL_LEADS
});
const recieveShopCommercialLeads = (json) => ({
    type: RECIEVE_SHOP_COMMERCIAL_LEADS,
    commercialLeads: json
});

const generateClOptions = (commercialLeads) => {
    commercialLeads.forEach((cl) => {
        cl.value = cl.idCommercialLead;
        cl.label = cl.commercialLeadName;
    });

    return commercialLeads;
}

export const fetchShopCommercialLeads = () => {
    return dispatch => {
        dispatch(requestShopCommercialLeads());
        return client.fetch({url: `${API_SERVER}/wp-json/wiaas/commercial-leads` })
            .then(response => {

                if(response.data){

                    const clOptions = generateClOptions(response.data.map(cl => ({
                        idCommercialLead: cl.id,
                        commercialLeadName: cl.name
                    })));

                    dispatch(recieveShopCommercialLeads(clOptions));

                    if (clOptions.length) {
                        dispatch(selectCommercialLead(clOptions[0]));
                        dispatch(fetchShopPackages(clOptions[0]));
                    }
            }
        })
        .catch(error => {
            client.onError(error, dispatch);
        });
    }
}

export const selectCommercialLead = (cl) => ({
    type: SELECT_SHOP_COMMERCIAL_LEAD,
    selectedCommercialLead: cl
});
