<?php
namespace Helpers\Outil;

class Color
{

    /**
     * Converts HSL color to RGB hex code
     * Input: Array(Hue, Saturation, Lightness) - Values from 0 to 1
     * Output: String hex value (#000000 - #FFFFFF)
     * @see https://github.com/hracik/php-color-converter
     * @param float[] $hsl [0.0;0.1]
     * @return string
     */
    public static function hsl2hex(array $hsl) :string
    {
        $rgb = self::hsl2rgb($hsl);
        return self::rgb2hex($rgb);
    }

    /**
     * Converts RGB color to hex code
     * Input: Array(Red, Green, Blue) - 0-255 each, int values
     * Output: String hex value (#000000 - #ffffff)
     * @see https://github.com/hracik/php-color-converter
     * @param int[] $rgb 0-255
     * @return string
     */
    public static function rgb2hex(array $rgb) :string
    {
        list($r,$g,$b) = $rgb;
        return sprintf("#%02X%02X%02X", $r, $g, $b);
    }

    /**
     * @see https://github.com/hracik/php-color-converter
     * @param float[] $hsl [0.0;0.1]
     * @return int[]
     */
    public static function hsl2rgb(array $hsl): array
    {
        list($h, $s, $l) = $hsl;
        $m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
        $m1 = $l * 2 - $m2;
        return array(
            0 => intval(round(self::_hue2rgb($m1, $m2, $h + 0.33333) * 255)),
            1 => intval(round(self::_hue2rgb($m1, $m2, $h) * 255)),
            2 => intval(round(self::_hue2rgb($m1, $m2, $h - 0.33333) * 255)),
        );
    }

    /**
     * Helper function for hsl2rgb().
     * @see https://github.com/hracik/php-color-converter
     * @param float $m1
     * @param float $m2
     * @param float $h
     */
    private static function _hue2rgb($m1, $m2, $h) :float
    {
        $h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
        if ($h * 6 < 1) {
            return $m1 + ($m2 - $m1) * $h * 6;
        }
        if ($h * 2 < 1) {
            return $m2;
        }
        if ($h * 3 < 2) {
            return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
        }
        return $m1;
    }
}
