import { getDocumentIcon } from './DocumentHelper';

const DEFAULT_PACKAGE_IMG = 'static/img/no-photo-package.jpg';

function extractPrices(wcPackageId, prices) {
    return prices.map(price => ({
        idPrice: price.id,
        idPaymentType: price.id,
        payType: price['payment_type'],
        isSameCompanyAsCl: false,
        idPackage: wcPackageId,
        periodUnit: price['period_unit'],
        maxContractPeriod: price['max_contract_period'],
        packagePayPeriod: price['package_pay_period'],
        servicesContractPeriod: price['services_contract_period'],
        fixedExtra: price['fixed_extra'],
        servicesExtra: price['services_extra'],
        recurrentExtra: price['recurrent_extra']
    }));
}

function extractGroups(wcPackageGroups) {
    const extractedGroups = {};

    Object.keys(wcPackageGroups).forEach(key => {
        const group = wcPackageGroups[key];
        extractedGroups[key] = {
            groupName: group.name,
            idGroup: group.id,
            options: group.options.map(option => ({
                idOptionPackage: option.id,
                optionName: option.name,
                isDefault: option.default,
                shortDescription: option.description,
                prices: extractPrices(option.id, option.prices),
            })),
        };
    });

    return extractedGroups;
}

export const fromWCPackage = wcPackage => {
    return {
        id: wcPackage.id,
        reference: wcPackage.reference,
        image: wcPackage.images[0].src || DEFAULT_PACKAGE_IMG,
        hasImage: !!wcPackage.images.length,
        name: wcPackage.name,
        country: wcPackage.country,
        countryCode: wcPackage['country_code'],
        currency: wcPackage.currency,
        documents: wcPackage.documents ? wcPackage.documents.map(document => {
            document.icon = getDocumentIcon(document.extension);
            return document;
        }) : [],
        shortDescription: wcPackage['short_description'],
        prices: extractPrices(wcPackage.id, wcPackage.prices || []),
        groups: extractGroups(wcPackage.groups || {}),
        additionalPackages: wcPackage['additional_packages'] ? wcPackage['additional_packages'].map(additionalPackage =>({
            idAdditionalPackage: additionalPackage.id,
            packageName: additionalPackage.name,
            shortDescription: additionalPackage.description,
            prices: extractPrices(additionalPackage.id, additionalPackage.prices)
        })) : [],
    }
};