import Utils from '../utils/index.mjs';
import channels from '../channels/reusable.mjs';

/* IMPORT */
/* MAIN */
const HSL = {
    /* VARIABLES */
    re: /^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,
    hueRe: /^(.+?)(deg|grad|rad|turn)$/i,
    /* HELPERS */
    _hue2deg: (hue) => {
        const match = hue.match(HSL.hueRe);
        if (match) {
            const [, number, unit] = match;
            switch (unit) {
                case 'grad': return Utils.channel.clamp.h(parseFloat(number) * .9);
                case 'rad': return Utils.channel.clamp.h(parseFloat(number) * 180 / Math.PI);
                case 'turn': return Utils.channel.clamp.h(parseFloat(number) * 360);
            }
        }
        return Utils.channel.clamp.h(parseFloat(hue));
    },
    /* API */
    parse: (color) => {
        const charCode = color.charCodeAt(0);
        if (charCode !== 104 && charCode !== 72)
            return; // 'h'/'H'
        const match = color.match(HSL.re);
        if (!match)
            return;
        const [, h, s, l, a, isAlphaPercentage] = match;
        return channels.set({
            h: HSL._hue2deg(h),
            s: Utils.channel.clamp.s(parseFloat(s)),
            l: Utils.channel.clamp.l(parseFloat(l)),
            a: a ? Utils.channel.clamp.a(isAlphaPercentage ? parseFloat(a) / 100 : parseFloat(a)) : 1
        }, color);
    },
    stringify: (channels) => {
        const { h, s, l, a } = channels;
        if (a < 1) { // HSLA
            return `hsla(${Utils.lang.round(h)}, ${Utils.lang.round(s)}%, ${Utils.lang.round(l)}%, ${a})`;
        }
        else { // HSL
            return `hsl(${Utils.lang.round(h)}, ${Utils.lang.round(s)}%, ${Utils.lang.round(l)}%)`;
        }
    }
};

export { HSL as default };
