import {
    API_SERVER
} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import PriceHelper from '../../helpers/coMarket/PriceHelper';
import {
    REQUEST_PACKAGE_DETAILS,
    RECIEVE_PACKAGE_DETAILS,
    SELECT_OPTION,
    SELECT_AGREEMENT,
    SELECT_ADDITIONAL,
    REMOVE_ADDITIONAL,
    REQUEST_ADD_TO_CART,
    CLEAR_SELECTIONS,
    coMarketMessages
} from '../../constants/coMarketConstants';
import {updateMessages} from '../notification/notificationActions';
import {fetchCartCount} from '../cart/cartActions';
import { fromWCPackage } from '../../helpers/PackageHelper';

const client = new HtmlClient();
const priceHelper = new PriceHelper();

const requestPackageDetails = () => ({
    type: REQUEST_PACKAGE_DETAILS,
    isLoading: true
});
const recievePackageDetails = (json) => ({
    type: RECIEVE_PACKAGE_DETAILS,
    isLoading: false,
    selectedPackage: json
});

const clearSelections = () => ({
    type: CLEAR_SELECTIONS,
    selectedOptions: null,
    selectedAdditionals: null,
    selectedAgreement: null
})

export const fetchPackageDetails = (params) => {
    return dispatch => {
        dispatch(requestPackageDetails());
        return client.fetch({
                url: `${API_SERVER}/wp-json/wc/v2/products/${params.idPackage}?shop_id=${params.shopId}`,
                method: 'get'
            })
            .then(response => {
                if(response.data){
                    const packageData = fromWCPackage(response.data);
                    dispatch(clearSelections());
                    if(packageData.prices && packageData.prices.length){
                        dispatch(selectAgreement(packageData.prices[0]));
                    }

                    if(packageData.groups){
                        Object.keys(packageData.groups).forEach((idGroup) => {
                            const defaultOption = packageData.groups[idGroup].options.find((option) => option.isDefault);
                            if(defaultOption){
                                dispatch(selectOption(idGroup, defaultOption));
                            }
                        });
                    }

                    dispatch(recievePackageDetails(packageData));
                }
            })
            .catch(error => {
                client.onError(error, dispatch);
            });
    }
}

const collectPackageOptionsAndAdditionals = (selectedOptions, selectedAdditionals, selectedAgreement) => {
    const optionPackages = [];
    const additionalPackages = [];
    const unavailablePackages = [];

    if(selectedAdditionals && selectedAdditionals.length){
        selectedAdditionals.forEach(additional => {
            const selectedPrice = priceHelper.getSelectedPrice(additional, selectedAgreement);
            if(!selectedPrice){
                unavailablePackages.push(additional);
            }else{
                additionalPackages.push(additional.idAdditionalPackage);
            }
        });
    }

    if(selectedOptions){
        Object.keys(selectedOptions).forEach(idGroup => {
            const selectedPrice = priceHelper.getSelectedPrice(selectedOptions[idGroup], selectedAgreement);
            if(!selectedPrice){
                unavailablePackages.push(selectedOptions[idGroup]);
            }else{
                optionPackages.push(selectedOptions[idGroup].idOptionPackage);
            }
        });
    }

    return {optionPackages, additionalPackages, unavailablePackages};
};

const requestAddToCart = () => ({
    type: REQUEST_ADD_TO_CART
});

export const addToCart = (addParams) => {
    const result = collectPackageOptionsAndAdditionals(
        addParams.selectedOptions,
        addParams.selectedAdditionals,
        addParams.selectedAgreement);

    if(result.unavailablePackages.length){
        const unavailable = result.unavailablePackages.map((unavailable) =>{return unavailable.optionName || unavailable.packageName;});
        const message = coMarketMessages.UNAVAILABLE_PACKAGES + ' ' + unavailable.join();
    
        return dispatch => {dispatch(updateMessages([{code: 'warning', message}], coMarketMessages))};
    }

    return dispatch => {
        dispatch(requestAddToCart());
        return client.fetch({
                url: `${API_SERVER}/wp-json/wiaas/cart/items`,
                method: 'post',
                data: {
                    'package_id': addParams.selectedPackage.id,
                    'price_id': addParams.selectedAgreement.idPrice,
                    'addons_ids': result.additionalPackages,
                    'options_ids': result.optionPackages,
                    'cl_id': addParams.shopId,
                },
            })
            .then(response => {
                if(response.data && response.data.messages){
                    dispatch(updateMessages(response.data.messages, coMarketMessages));
                    dispatch(fetchCartCount());
                }
            })
            .catch(error => {
                client.onError(error, dispatch);
            });
    }
};

export const selectAgreement = (agreement) => {
        return {
            type: SELECT_AGREEMENT,
            selectedAgreement: agreement,
        };
};

export const selectOption = (idGroup, option) => {
        const selectedOption = {};
        selectedOption[idGroup] = option;

        return {
            type: SELECT_OPTION,
            selectedOptions: selectedOption,
        };
};

export const selectAdditional = (additional) => ({
        type: SELECT_ADDITIONAL,
        selectedAdditonal: additional,
});

export const removetAdditional = (additional) => ({
        type: REMOVE_ADDITIONAL,
        selectedAdditonal: additional,
});
