import { getUrl } from '../../Utils/getUrl';
import { fetchDataAsync } from '../Actions';

export const RECEIVE_FONTS = 'RECEIVE_FONTS';
export const ADD_FONT = 'ADD_FONT';
export const ADD_FONTS = 'ADD_FONTS';

export const addFontFamilyToDOM = (name, url, bold, italic) => {
    const fontFaceProperties = ['font-family: "' + name + '";', 'src: url("' + url + '");'];

    if (bold) {
        fontFaceProperties.push('font-weight: bold;');
    }

    if (italic) {
        fontFaceProperties.push('font-style: italic;');
    }

    const style = document.createElement('style');

    style.appendChild(document.createTextNode('@font-face { ' + fontFaceProperties.join(' ') + ' }'));

    document.head.appendChild(style);
};

export const receiveFonts = data => dispatch => {
    const fonts = [];

    for (const customFont of data) {
        const font = {
            name: customFont.name,
            family: customFont.name,
            regular: false,
            bold: false,
            italic: false,
            boldItalic: false,
            isDefault: customFont.isDefault,
        };

        const fontFields = [
            { field: 'fileNameRegular', property: 'regular', bold: false, italic: false },
            { field: 'fileNameBold', property: 'bold', bold: true, italic: false },
            { field: 'fileNameItalic', property: 'italic', bold: false, italic: true },
            { field: 'fileNameBoldItalic', property: 'boldItalic', bold: true, italic: true },
        ];

        for (const fontField of fontFields) {
            const fontPath = customFont[fontField.field];

            if (fontPath) {
                const fontUrl = getUrl(fontPath);
                const urlFieldName =
                    'url' + fontField.property.charAt(0).toUpperCase() + fontField.property.slice(1);

                font[fontField.property] = true;
                font[urlFieldName] = fontUrl;

                addFontFamilyToDOM(font.family, fontUrl, fontField.bold, fontField.italic);
            }
        }

        fonts.push(font);
    }

    dispatch({
        type: RECEIVE_FONTS,
        data: fonts,
    });
};

export const fetchFonts = () => fetchDataAsync('designer/fonts', receiveFonts);

export const addCustomFont = customFont => ({
    type: ADD_FONT,
    data: customFont,
});

export const addCustomFonts = customFonts => ({
    type: ADD_FONTS,
    data: customFonts,
});
