
import { themeBaseColors, colorTransforms } from '../constants/colors';

const CACHE_VAR_NAME = 'mp2-theme-colors';
const cachedValues = localStorage && localStorage.getItem(CACHE_VAR_NAME);
const currentValues = (cachedValues && JSON.parse(cachedValues)) || {};
const docReady = new Promise(resolve => {
    document.addEventListener('DOMContentLoaded', resolve);
}).catch(e => console.error(e));

const recompute = (forceSet = false) => {
    const computedStyle = getComputedStyle(document.body);

    const newColors = themeBaseColors.map(baseName => {
        let baseColor = computedStyle.getPropertyValue(`--${baseName}`);
        baseColor = baseColor && baseColor.trim();
        const hasChanged = currentValues[baseName] !== baseColor;
        currentValues[baseName] = baseColor;
        return (forceSet || hasChanged) && {
            baseName,
            baseColor
        };
    }).filter(a => a);

    newColors.reduce((carry, { baseName, baseColor }) => (
        colorTransforms.reduce((inner, transform) => {
            const value = baseColor && transform.rule(baseColor);
            const varName = `--${baseName}${transform.name}`;
            inner.push({ varName, value });
            return inner;
        }, carry)
    ), []).forEach(change => {
        document.body.style.setProperty(change.varName, change.value);
    });

    localStorage && localStorage.setItem(CACHE_VAR_NAME, JSON.stringify(currentValues));
};

docReady.then(() => {
    recompute(true);

    const onMutation = mutationsList => {
        mutationsList.forEach(mutation => {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                recompute();
            }
        });
    };
    const observer = new MutationObserver(onMutation);
    observer.observe(document.body, { attributes: true, childList: false, subtree: false });
});
