import FontFaceObserver from 'fontfaceobserver';
import { traverse } from 'redhotmagma-graphics-editor/Utils/DOM';
import { getConf } from '../../../configuration';

export const removeQuotes = str => str && str.replace(/"/g, '');

export const FontFaceRepository = (({ loadTimeout }) => {
    const repository = new Map();

    const request = (name, params = {}) => {
        const key = [name, ...Object.values(params)].join('-');
        if (!repository.has(key)) {
            const fontFaceObserver = new FontFaceObserver(name, params);
            repository.set(key, fontFaceObserver.load(null, loadTimeout));
        }
        return repository.get(key);
    };

    const collectFromElement = element => {
        const fonts = [];
        traverse(element, node => {
            if (node.style && node.style.fontFamily) {
                const {
                    style: { fontFamily, fontWeight, fontStyle },
                } = node;
                fonts.push(
                    request(removeQuotes(fontFamily), {
                        weight: fontWeight || 'normal',
                        style: fontStyle || 'normal',
                    })
                );
            }
        });
        return Promise.all(fonts);
    };

    const collectFromHTML = htmlStr => {
        const element = document.createElement('div');
        element.innerHTML = htmlStr;
        return collectFromElement(element);
    };

    return {
        request,
        collectFromElement,
        collectFromHTML,
    };
})({
    loadTimeout: getConf('network.timeout', 60000),
});
