import {
    API_SERVER
} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_SHOP_PACKAGES,
    RECIEVE_SHOP_PACKAGES,
    REQUEST_SHOPS,
    RECEIVE_SHOPS,
    SELECT_SHOP
} 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 = (shop, search) => {
    return dispatch => {
        dispatch(requestShopPackages());
        let searchParam = search ?  '?search=' +search : ''

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

const requestShops = () => ({
    type: REQUEST_SHOPS
});
const receiveShops = (json) => ({
    type: RECEIVE_SHOPS,
    shops: json
});

const generateShopOptions = (shops) => {
    shops.forEach((shop) => {
        shop.value = shop.id;
        shop.label = shop.name;
    });

    return shops;
}

export const fetchShops = (userId) => {
    return dispatch => {
        dispatch(requestShops());

        return client.fetch({url: `${API_SERVER}/wp-json/wiaas/customer/${userId}/shops` })
            .then(response => {

                if(response.data){

                    const shopOptions = generateShopOptions(response.data);

                    dispatch(receiveShops(shopOptions));

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

export const selectShop = (shopInfo) => ({
    type: SELECT_SHOP,
    selectedShop: shopInfo
});
