import { CTA_LEAD_GEN, CTA_UPGRADE } from '../constants/actions';

const getPricingPlanId = ({ id, plans = [] }) => {
    if (plans && plans.length) {
        return plans[0].uuid;
    }
    return id;
};

const getAddonIds = addons => addons.map(addon => getPricingPlanId(addon.edition[0]));

const getCartLink = (selectedEdition = {}, selectedAddons = [], urlCreator = {}) => {
    const url = urlCreator.base;
    const addonIds = getAddonIds(selectedAddons);
    const params = [
        `${urlCreator.editionParam}=${getPricingPlanId(selectedEdition)}`,
        ...addonIds.map(addonId => `${urlCreator.addonParam}=${addonId}`)
    ].join('&');
    const glue = url.indexOf('?') === -1 ? '?' : '&';
    return `${url}${glue}${params}`;
};

export const filterProductActions = cta => {
    if (!cta) {
        return null;
    }

    return cta.actionType !== CTA_UPGRADE;
};

export const filterBundleActions = cta => {
    if (!cta) {
        return null;
    }

    return cta.actionType !== CTA_LEAD_GEN;
};

export const parsePricingAction = (action = {}) => {
    const transformedAction = { ...action };
    if (action.actionType === CTA_LEAD_GEN) {
        transformedAction.url = action.leadPageUrl;
    }
    return transformedAction;
};

export const parsePricingActions = actions => ({
    caption: actions && actions.caption ? { ...actions.caption } : undefined,
    items: actions && actions.items ? actions.items.filter(filterProductActions).map(parsePricingAction) : []
});

export const handleBuyAction = (action, edition, addons) => {
    const redirectCartLink = getCartLink(
        edition,
        addons,
        action.urlCreator,
    );
    window.location.assign(redirectCartLink);
};

export const handleAddToCartAction = (action, edition, addons) => {
    window.AD_addToCart(
        getPricingPlanId(edition),
        getAddonIds(addons)
    );
};

export const handleFollowUrlAction = action => {
    window.location.assign(action.url);
};
