'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var index = require('../utils/index.js');
var reusable = require('../channels/reusable.js');

/* 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 index.default.channel.clamp.h(parseFloat(number) * .9);
                case 'rad': return index.default.channel.clamp.h(parseFloat(number) * 180 / Math.PI);
                case 'turn': return index.default.channel.clamp.h(parseFloat(number) * 360);
            }
        }
        return index.default.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 reusable.default.set({
            h: HSL._hue2deg(h),
            s: index.default.channel.clamp.s(parseFloat(s)),
            l: index.default.channel.clamp.l(parseFloat(l)),
            a: a ? index.default.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(${index.default.lang.round(h)}, ${index.default.lang.round(s)}%, ${index.default.lang.round(l)}%, ${a})`;
        }
        else { // HSL
            return `hsl(${index.default.lang.round(h)}, ${index.default.lang.round(s)}%, ${index.default.lang.round(l)}%)`;
        }
    }
};

exports.default = HSL;
