#include "kk_color_space.h"

void RGB_to_HSL_base(unsigned char red, unsigned char green, unsigned char blue,double *H,double *S,double *L)
{
    double min=0, max=0, delta=0;
    double R=0, G=0, B=0;

    R = red / 255.0;
    G = green / 255.0;
    B = blue / 255.0;

    min = (R < G) ? ((R < B) ? R : B):((G < B) ? G : B);
    max = (R > G) ? ((R > B) ? R : B):((G > B) ? G : B);

    delta = max - min;

    *L = (min + max) / 2.0;

    if(*L==0.0 || (max-min) == 0.0){
        *S = 0;
    }else if(*L > 0.5){
        *S = delta / (2 - 2 * *L);
    }else{
        *S = delta / (2 * *L);
    }

    if((max-min) == 0.0){
       *H = 0;
    }else if((max-R == 0.0) && (G >= B)){
       *H = (G - B) / delta;
    }else if((max-R == 0.0) && (G < B)){
       *H = (G - B) / delta + 6;
    }else if((max-G) == 0.0){
       *H = (B - R) / delta + 2;
    }else if((max-B) == 0.0){
       *H = (R - G) / delta + 4;
    }else{

    }
    *H /= 6.0;
}
void RGB_to_HSL(unsigned char red, unsigned char green, unsigned char blue,unsigned short *H,unsigned char *S,unsigned char *L)
{
    double h, s, l;
    RGB_to_HSL_base(red,green,blue,&h,&s,&l);
    *H = h * 360 + ((int)(h * 3600) % 10 >= 5 ? 1 : 0);
    *S = s * 100 + ((int)(s * 1000) % 10 >= 5 ? 1 : 0);
    *L = l * 100 + ((int)(l * 1000) % 10 >= 5 ? 1 : 0);
}

double HSL_convert_color_to_RGB(double p, double q, double tC)
{
    tC = (tC < 0) ? (tC + 1) : ((tC > 1) ? (tC - 1) : tC);

    if(tC * 6 < 1){
        return (p + (q - p) * 6 * tC );
    }else if(tC * 2 < 1){
        return q;
    }else if(tC * 3 < 2){
        return p + ((q - p) * 6 * (2 / 3.0 - tC));
    }
    else{
        return p;
    }
}
void HSL_to_RGB_base(double H,double S,double L,unsigned char *red, unsigned char *green, unsigned char *blue)
{
    double q, p;
    double tR, tG, tB;
    double r, g, b;

    q = (L <= 0.5) ? L * (S + 1) : L + S - (L * S);
    p = 2 * L  - q;

    tR = H + 1/3.0;
    tG = H;
    tB = H - 1/3.0;

    r = 255 * HSL_convert_color_to_RGB(p, q, tR);
    g = 255 * HSL_convert_color_to_RGB(p, q, tG);
    b = 255 * HSL_convert_color_to_RGB(p, q, tB);

    *red = r + (((int)(r * 10)  % 10 >= 5) ? 1 : 0);
    *green = g + (((int)(g * 10) % 10 >= 5) ? 1 :0);
    *blue = b + (((int)(b * 10) % 10 >= 5) ? 1 : 0);
}

void HSL_to_RGB(unsigned short H,unsigned char S,unsigned char L,unsigned char *red, unsigned char *green, unsigned char *blue)
{
   double h = H / 360.0;
   double s = S / 100.0;
   double l = L / 100.0;
   HSL_to_RGB_base(h,s,l,red,green,blue);
}


