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';

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}/coMarket/api/getShopPackageDetails`,
                method: 'post',
                data: params
            })
            .then(response => {
                if(response.data){
                    const jsonData = response.data;
                    dispatch(clearSelections());
                    if(jsonData.prices && jsonData.prices.length){
                        dispatch(selectAgreement(jsonData.prices[0]));
                    }

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

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

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

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

    return {extraPackages, unavailablePackages};
};

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

export const addToCart = (addParams) => {
    const options = generateOptions(addParams.selectedOptions, addParams.selectedAdditionals, addParams.selectedAgreement);

    const params = {
        idPackage: addParams.selectedPackage.packageInfo.idPackage,
        idPrice: addParams.selectedAgreement.idPrice,
        options: options.extraPackages
    };

    if(options.unavailablePackages.length){
        const unavailable = options.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}/coMarket/api/addToCart`,
                method: 'post',
                data: params
            })
            .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,
});
