import first from 'lodash/first';
import each from 'lodash/each';
import find from 'lodash/find';
import get from 'lodash/get';
import createSelector from '../../../Utils/Function/createSelector';

const escapeQuotes = str => str.replace(/(['"])/g, '\\$1');

export function getDefaultFont(state) {
    const fonts = state.fonts;
    return find(fonts, { isDefault: true }) || first(fonts);
}

export const getDefaultFontParams = (state, stringify = true) => {
    const defaultFont = getDefaultFont(state);
    const fontParams = {
        'font-family': `"${escapeQuotes(defaultFont.family)}"`,
        'font-weight': 'normal',
        'font-style': 'normal',
    };
    return stringify
        ? Object.keys(fontParams)
              .map(prop => `${prop}: ${fontParams[prop]};`)
              .join(' ')
        : fontParams;
};

export const getFontMapping = createSelector(
    ({ fonts }) => fonts,
    fonts => {
        const typeToUrlProp = {
            regular: 'urlRegular',
            bold: 'urlBold',
            italic: 'urlItalic',
            boldItalic: 'urlBoldItalic',
        };
        const typeKeys = Object.keys(typeToUrlProp);
        const fontMapping = {};
        each(fonts, font => {
            fontMapping[font.family] = {};
            each(typeKeys, typeKey => {
                const fontUrl = font[typeToUrlProp[typeKey]];
                if (fontUrl) {
                    fontMapping[font.family][typeKey] = fontUrl;
                }
            });
        });
        return fontMapping;
    }
);

export function getUsedCustomFontsInEditor(state) {
    const usedCustomFonts = [];
    const designdata = get(state, 'configurator.configuration.designdata') || {};
    Object.values(designdata).forEach(designAreaData => {
        const objects = get(designAreaData, 'canvasData.objects') || [];
        objects
            .filter(({ type }) => type === 'Text')
            .forEach(({ fontItem }) => {
                if (fontItem.isCustomFont) {
                    const customFontObj = {
                        ...getDefaultFont(state),
                        ...fontItem,
                    };
                    !find(usedCustomFonts, customFontObj) && usedCustomFonts.push(customFontObj);
                }
            });
    });
    return usedCustomFonts;
}
