namespace salesbook.Shared.Core.Utility;

public static class UtilityColor
{
    public static string CalcHexColor(string input)
    {
        try
        {
            var hue = (int)(Math.Abs(input.GetHashCode()) * 137.508 % 360);

            var data = new HSL(hue, 0.90f, 0.85f);
            var myColor = HSLToRGB(data);

            return myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return "dddddd";
        }
    }

    private struct RGB(byte r, byte g, byte b)
    {
        public byte R
        {
            get => r;
            set => r = value;
        }

        public byte G
        {
            get => g;
            set => g = value;
        }

        public byte B
        {
            get => b;
            set => b = value;
        }

        public bool Equals(RGB rgb)
        {
            return (this.R == rgb.R) && (this.G == rgb.G) && (this.B == rgb.B);
        }
    }

    private struct HSL(int h, float s, float l)
    {
        public int H
        {
            get => h;
            set => h = value;
        }

        public float S
        {
            get => s;
            set => s = value;
        }

        public float L
        {
            get => l;
            set => l = value;
        }

        public bool Equals(HSL hsl)
        {
            return H == hsl.H && (this.S == hsl.S) && (this.L == hsl.L);
        }
    }

    private static RGB HSLToRGB(HSL hsl)
    {
        byte r;
        byte g;
        byte b;

        var hue = (float)hsl.H / 360;
        if (hsl.S == 0)
        {
            r = g = b = (byte)(hsl.L * 255);
        }
        else
        {
            var v2 = hsl.L < 0.5 ? hsl.L * (1 + hsl.S) : hsl.L + hsl.S - hsl.L * hsl.S;
            var v1 = 2 * hsl.L - v2;

            r = (byte)(255 * HueToRGB(v1, v2, hue + 1.0f / 3));
            g = (byte)(255 * HueToRGB(v1, v2, hue));
            b = (byte)(255 * HueToRGB(v1, v2, hue - 1.0f / 3));
        }

        return new RGB(r, g, b);
    }

    private static float HueToRGB(float v1, float v2, float vH)
    {
        if (vH < 0)
            vH += 1;

        if (vH > 1)
            vH -= 1;

        if (6 * vH < 1)
            return v1 + (v2 - v1) * 6 * vH;

        if (2 * vH < 1)
            return v2;

        if (3 * vH < 2)
            return v1 + (v2 - v1) * (2.0f / 3 - vH) * 6;

        return v1;
    }
}