/***************************** 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 <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_;

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;
	}
	
	
  	QString s="RGB(";
    	s+=QString::number(col.redF(),'g',2)+ "," +
       		QString::number(col.greenF(),'g',2)+ "," +
       		QString::number(col.blueF(),'g',2)+ ")";
		
	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;
			}
			
			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;
}

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