/* https://gist.github.com/ReedD/8b216b75e00ff20ceae2 */

/* Returns luma in percentage */
function luma(r, g, b, a) {

    if (arguments.length === 1) {
        let match;
        const colorString = String(r);
        const hexRegex = /^#?([a-fA-F\d]{6}|[a-fA-F\d]{3})$/;
        const rgbRegex = /^rgb\((\d{1,3}),[ +]?(\d{1,3}),[ +]?(\d{1,3})\)$/;
        const rgbaRegex = /^rgba\((\d{1,3}),[ +]?(\d{1,3}),[ +]?(\d{1,3}),[ +]?(\d|\d?\.\d+)\)$/;
        if (colorString.match(hexRegex)) {
            match = colorString.match(hexRegex)
            let hex = match[0];
            if (hex.length === 4) {
                // Convert to 6
                hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
            }

            r = parseInt("0x" + hex[1] + hex[2], 16);
            g = parseInt("0x" + hex[3] + hex[4], 16);
            b = parseInt("0x" + hex[5] + hex[6], 16);

        } else if (colorString.match(rgbRegex)) {
            match = colorString.match(rgbRegex)

            r = parseFloat(match[1]);
            g = parseFloat(match[2]);
            b = parseFloat(match[3]);
        } else if (colorString.match(rgbaRegex)) {
            match = colorString.match(rgbaRegex)

            r = parseFloat(match[1]);
            g = parseFloat(match[2]);
            b = parseFloat(match[3]);
        }
    } else {
        r = parseFloat(r) || 0;
        g = parseFloat(g) || 0;
        b = parseFloat(b) || 0;
    }
    // per ITU-R BT.709
    return Math.ceil(((0.2126 * r + 0.7152 * g + 0.0722 * b) * 100) / 255);
}

/* Contrast by standard from https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
*  and https://lesscss.org/functions/#color-operations-contrast
* */
function contrast(color, dark, light, threshold) {
    let t = threshold === undefined ? 43 : threshold;
    let d = dark === undefined ? '#000000' : dark;
    let l = light === undefined ? '#FFFFFF' : light;
    const hexRegex = /#(?:[\da-fA-F]{3}){1,2}$/;
    if (color.match(hexRegex)) {
        let lum = luma(color)
        if (lum > t) {
            return d;
        } else {
            return l;
        }
    }
}

function hexToRGB(h) {
    let r = 0, g = 0, b = 0;

    // 3 digits
    if (h.length === 4) {
        r = "0x" + h[1] + h[1];
        g = "0x" + h[2] + h[2];
        b = "0x" + h[3] + h[3];

        // 6 digits
    } else if (h.length === 7) {
        r = "0x" + h[1] + h[2];
        g = "0x" + h[3] + h[4];
        b = "0x" + h[5] + h[6];
    }

    return [r, g, b];
}