/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQPalette.h"

#include <QDebug>
#include <QPainter>

#include <algorithm>
#include <ctype.h>

#include "ConfigLoader.h"
#include "Tokenizer.h"

std::vector<string>  MvQPalette::names_;
std::map<std::string,MvQPaletteItem> MvQPalette::items_;
std::vector<std::string> MvQPalette::pseudoColourNames_;

static const float toRadFactor=3.14159265359/180.;
static const float toDegFactor=180./3.14159265359;

//reference values for the XYZ colour model.Observer= 2 deg, illuminant= D65
static float REF_X=95.047;
static float REF_Y=100.000;
static float REF_Z=108.883;

static void rgbToXyz(float r,float g, float b,float& x, float& y,float& z);
static void xyzToRgb(float x, float y,float z,float &r,float &g, float &b);
static void xyzToHcl(float x, float y,float z,float& h, float &c, float &l);
static void hclToXyz(float h,float c,float l,float& x, float& y,float& z);

//Please note that this tutorial was designed to be used only at the ECMWF.

void MvQPalette::load(request* r)
{
	// populate our list of 'special'/'pseudo' colour names	
	if(pseudoColourNames_.empty())
	{	  	
		pseudoColourNames_.push_back("AUTOMATIC");
		pseudoColourNames_.push_back("CONTOUR_LINE_COLOUR");
		pseudoColourNames_.push_back("BACKGROUND");
		pseudoColourNames_.push_back("FOREGROUND");
	}

  	const char* fname = get_value(r,"colour_file",0);
	if(!fname) return;

	FILE *f = fopen(fname, "r");

	if (!f) return;

	char line[500];
	char color[80];
	char name[80];

	while(fgets(line,sizeof(line),f))
	{
		char *p = line;
		int  i = 0;

		sscanf(p,"%s ; %s",color,name);
		while(*p && !i)
		{
			
			if(*p == '#')
			{
				color[i++] = *p++;
				while(*p && isxdigit(*p))
					color[i++] = *p++;
				color[i] = 0;
				if(i != 4 && i != 7 && i != 13)
					i = 0;
			}
			p++;
		}
		if(i) 
		{
			bool pseudo=MvQPalette::isPseudo(name);
		  	names_.push_back(name);
			items_[name]=MvQPaletteItem(name,
						    (pseudo)?QColor():MvQPalette::hexaCharToColour(color),pseudo);	
		}
	}

	fclose(f);
}

bool  MvQPalette::isPseudo(const std::string& name)
{
  	if(pseudoColourNames_.empty() == false &&
	    std::find(pseudoColourNames_.begin(),pseudoColourNames_.end(),name) != pseudoColourNames_.end())
	  	return true;
	
	return false;
}	

QColor MvQPalette::hexaCharToColour(const char *hexaChar)
{
	if(strlen(hexaChar) == 13)
	{  
        unsigned int r, g, b;
		char cval[5];
		
        strncpy(cval,hexaChar+1,4);
		cval[4]='\0';		
		sscanf(cval,"%x",&r);
		
		strncpy(cval,hexaChar+5,4);
		cval[4]='\0';		
		sscanf(cval,"%x",&g);
		
		strncpy(cval,hexaChar+9,4);
		cval[4]='\0';		
		sscanf(cval,"%x",&b);
		
		return QColor(r/256,g/256,b/256);		
	}
	
	return QColor();
}					
	
	
void MvQPalette::scan(PaletteScanner& p)
{
	for(vector<string>::iterator j = names_.begin(); j != names_.end(); ++j)
	{
	  	if(!isPseudo(*j))
		{
			map<std::string,MvQPaletteItem>::iterator it=items_.find(*j);
			if(it != items_.end())
			{
		  		p.next(*j,it->second.col_,it->second.pseudo_);
			}
		}	
	}	
}

string MvQPalette::toString(QColor col)
{
 	for(map<std::string,MvQPaletteItem>::iterator it = items_.begin(); it != items_.end(); it++)
	{
	  	if(it->second.pseudo_  == false && it->second.col_ ==col)
		  	return it->first;
	}
		
    bool hasAlpha=(col.alpha() != 255);

  	QString s="RGB(";
    if(hasAlpha)
        s="RGBA(";

    s+=QString::number(col.redF(),'g',4)+ "," +
            QString::number(col.greenF(),'g',4)+ "," +
            QString::number(col.blueF(),'g',4);

    if(!hasAlpha)
    {
        s+= ")";
    }
    else
    {
       s+="," + QString::number(col.alphaF(),'g',4) + ")";
    }
		
	return s.toStdString();	 
}  

QColor MvQPalette::magics(const string& name)
{
	QColor col;
	
	map<std::string,MvQPaletteItem>::iterator it = items_.find(name);
	if(it != items_.end())
	{
	  	col=it->second.col_;
	}
	else
	{  	
		Tokenizer parse("(, )");
		vector<string> v;

		parse(name,v);

		// Try rgb, hsl
        if(v.size() >= 4)
		{
			double x1 = atof(v[1].c_str());
			double x2 = atof(v[2].c_str());
			double x3 = atof(v[3].c_str());

			switch(v[0][0])
			{
			case 'r':
			case 'R':
				col = QColor::fromRgbF(x1,x2,x3);
				break;

			case 'h':
			case 'H':
				col = QColor::fromHslF(x1/360.,x2,x3); 
				break;
				
			default: 
			  	break;
			}

            //Alpha
            if(v.size() == 5)
            {
                double x4 = atof(v[4].c_str());
                col.setAlphaF(x4);
            }

			if(col.isValid())
			{	  	
				//colors[name] = col;
			}					
		}
		else if(name.empty())
		{
		  	col=QColor(Qt::blue);
		}
		else if(MvQPalette::isPseudo(name))
		{
		  	names_.push_back(name);
			items_[name]=MvQPaletteItem(name,QColor(),true);
		}				    
	}
	
	//colors[name] = c;
	//return PaletteRGBColor(palette,&c);
	
	return col;
}

void MvQPalette::toHclF(QColor c,float& hue, float& chroma,float& luminance)
{
    float x,y,z;
    rgbToXyz(c.redF(),c.greenF(),c.blueF(),x,y,z);
    qDebug()  << "xyz" << x << y << z;
    xyzToHcl(x,y,z,hue,chroma,luminance);
    if(c.red() == 255 && c.green() == 255 && c.blue() == 255)
        hue=40./360.;
}

QColor MvQPalette::fromHclF(float hue, float chroma,float luminance)
{
    float x,y,z,r,g,b;
    hclToXyz(hue,chroma,luminance,x,y,z);
    xyzToRgb(x,y,z,r,g,b);
    return QColor::fromRgbF(r,g,b);
}


//paint the chequered background when alpha is set
void MvQPalette::paintAlphaBg(QPainter* painter,QRect area)
{
    painter->save();
    painter->setClipRect(area);

    QColor c1(170,170,170);
    QColor c2(190,190,190);
    int rs=8;
    int nx=area.width()/rs;
    int ny=area.height()/rs;
    QColor cAct=c1;
    for(int i=0; i <= nx; i++)
        for(int j=0; j <= ny; j++)
    {
        QRect r(area.x()+1+i*rs,area.y()+1+j*rs,rs,rs);
        if(j%2 ==0)
        {
            if(i%2 == 0) cAct=c1;
            else cAct=c2;
        }
        else
        {
            if(i%2 == 0) cAct=c2;
            else cAct=c1;
        }
        painter->fillRect(r,cAct);
    }
    painter->restore();
}

// r,g,b : 0-1
// x,y,z: 0-100
void rgbToXyz(float r,float g, float b,float& x, float& y,float& z)
{
    if(r > 0.04045)
        r=pow((r+0.055)/1.055,2.4);
    else
        r = r/12.92;

    if(g > 0.04045 )
        g=pow((g + 0.055)/1.055,2.4);
    else
        g=g/12.92;

    if(b > 0.04045)
        b=pow((b + 0.055)/1.055,2.4);
    else
        b =b/12.92;

    r*=100;
    g*=100;
    b*=100;

    x = r*0.4124+g*0.3576+b*0.1805;
    y = r*0.2126+g*0.7152+b*0.0722;
    z = r*0.0193+g*0.1192+b*0.9505;
}

// x,y,z: 0-100
// r,g,b : 0-1
void xyzToRgb(float x, float y,float z,float &r,float &g, float &b)
{
    x=x/100.;        //x from 0 to  95.047
    y=y/100.;        //y from 0 to 100.000
    z=z/100.;        //z from 0 to 108.883

    r=x*3.2406 + y *(-1.5372) + z *(-0.4986);
    g=x*(-0.9689) + y *  1.8758 + z*  0.0415;
    b=x* 0.0557 + y*(-0.2040) + z*  1.0570;

    if(r> 0.0031308)
        r= 1.055 * pow(r,1./2.4) - 0.055;
    else
        r= 12.92 * r;

    if(g > 0.0031308 )
        g = 1.055 * pow(g,1./2.4) - 0.055;
    else
        g = 12.92 * g;

    if(b > 0.0031308 )
        b = 1.055 * pow(b,1./2.4) - 0.055;
    else
        b = 12.92 * b;

    if(r>1.) r=1.;
    if(g>1.) g=1.;
    if(b>1.) b=1.;

    if(r<0.) r=0.;
    if(g<0.) g=0.;
    if(b<0.) b=0.;
}

// x,y,z: 0-100
// h,c,l : 0-1
void xyzToHcl(float x, float y,float z,float& h, float &c, float &l)
{
    x/=REF_X;
    y/=REF_Y;
    z/=REF_Z;

    if(x> 0.008856)
        x=pow(x,1./3.);
    else
        x=(7.787*x) + (16./116.);

    if(y > 0.008856)
        y = pow(y,1./3.);
    else
        y = (7.787*y) + ( 16. / 116. );

    if(z> 0.008856)
        z=pow(z,1./3.);
    else
        z = (7.787 * z) + ( 16. / 116. );

    l = ( 116. * y )-16.;
    float a = 500.*(x-y);
    float b = 200.*(y-z);

    qDebug() << "   abl" << a << b << l;

    h = atan2(b,a);

    qDebug() << "   h1" << h;

    if(h>0)
        h = h*toDegFactor;
    else
        h = 360.+h*toDegFactor;

    qDebug() << "   h2" << h;

    h=h/360.;
    c = sqrt(a*a + b*b);
}

// h,c,l : 0-1
// x,y,z: 0-100
void hclToXyz(float h,float c,float l,float& x, float& y,float& z)
{
    float a = cos(360*h*toRadFactor) * c;
    float b = sin(360*h*toRadFactor) * c;

    y=(l + 16.)/116.;
    x=a/500.+ y;
    z=y-b/200.;

    if(pow(y,3) > 0.008856 )
        y=pow(y,3);
    else
        y=(y - 16./116.)/7.787;

    if(pow(x,3) > 0.008856)
        x=pow(x,3);
    else
       x=(x-16./116.)/7.787;

    if(z > 0.008856 )
        z=pow(z,3);
    else
        z=(z-16./116.)/7.787;

    x*=REF_X;
    y*=REF_Y;
    z*=REF_Z;
}

static SimpleLoader<MvQPalette> load("resources",0);
