/***************************** 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 "MvQColourLine.h"

#include <QComboBox>
#include <QDebug>
#include <QPainter>

#include "MvQPalette.h"
#include "MvQRequestPanelHelp.h"

#include "LineFactory.h"
#include "RequestPanel.h"

MvQColourLine::MvQColourLine(RequestPanel& owner,const Parameter& param) :
		   MvQRequestPanelLine(owner,param) 
{
	colCb_ = new QComboBox(parentWidget_);
	
	QFont font;
    	QFontMetrics fm(font);
    	int h=fm.height()+4;
   	int w=h*2;
	colCb_->setIconSize(QSize(w,h));
	   
	param_.scan(*this);
	
	owner_.addWidget(colCb_,row_,3);
	
	connect(colCb_,SIGNAL(currentIndexChanged(int)),
		this,SLOT(slotCurrentChanged(int)));
}

void MvQColourLine::next(const Parameter&, const char* first,const char* /*second*/)
{
	addColour(MvQPalette::magics(first),QString::fromStdString(param_.beautifiedName(first)),QString(first));
}

void MvQColourLine::setColour(int idx,QColor col)
{
 	if(idx < 0 || idx > colCb_->count()-1)
	  	return;
	
  	QIcon icon;
   
      	if(pix_.isNull())
	{   
 		int w=colCb_->iconSize().width();
    		int h=colCb_->iconSize().height();
    		pix_=QPixmap(w, h);
		pix_.fill(Qt::transparent);
	}
    
    	QPainter painter(&pix_);
  	
	if(col.isValid())
	{
		painter.setPen(Qt::black);
		painter.setBrush(QBrush(col));
		painter.drawRect(1, 1, pix_.width()-2,pix_.height()-2);	  
	}
	else
	{
	  	pix_.fill(Qt::transparent);
	  	//painter.setBrush(Qt::white);
		painter.setPen(QPen(Qt::gray,0.,Qt::DashLine));
		painter.drawRect(1, 1, pix_.width()-2,pix_.height()-3);	  
	}	
	
    	icon.addPixmap(pix_);
    
	colCb_->setItemIcon(idx,icon);
}	


void MvQColourLine::addColour(QColor color,QString name, QString realName,bool setCurrent)
{
    bool pseudoCol = MvQPalette::isPseudo(realName.toStdString()); 
     
    if(!color.isValid() && !pseudoCol) 
      	return;
    
    for(int i=0; i < colCb_->count(); i++)
    {
      	if(name.compare(colCb_->itemText(i),Qt::CaseInsensitive) == 0) 
	{
	  	if(setCurrent)
		{
		  	colCb_->setCurrentIndex(i);
		}
		return;
	}	
    }
    
    int idx=-1;
    if(colCb_->count() == 0)
    {
      	colCb_->addItem(name,realName);
    	idx=0;
    }		
    else
    {
      	int i=0;
    	while(i < colCb_->count() && colCb_->itemText(i) < name) 
		 i++;
	
	idx=i;
	colCb_->insertItem(idx,name,realName);
	if(setCurrent)
	  	colCb_->setCurrentIndex(idx);
    }	
    
   if(idx !=-1)
   {  
    	setColour(idx,color);
   }	
    
}

//There can be only one custom colour
void MvQColourLine::setCustomColour(QColor color,QString name, QString realName,bool setCurrent)
{
    	if(!color.isValid()) 
      		return;
   
    	int idx=-1;
   	for(int i=0; i < colCb_->count(); i++)
   	{
	  	if(colCb_->itemText(i).indexOf("rgb(",0,Qt::CaseInsensitive) !=- 1) 
		{
	  		idx=i;
			break;
		}
    	}

    	//Need to create a custom colour
    	if(idx == -1)
   	{  
    		if(colCb_->count() == 0)
		{
		  	colCb_->addItem(name,realName);
			idx=1;
		}	
    		else
    		{
      			int i=0;
    			while(i < colCb_->count() && colCb_->itemText(i) < name) 
			 	i++;
		
			idx=i;
			colCb_->insertItem(idx,name,realName);
			if(setCurrent)
	  			colCb_->setCurrentIndex(idx);
    		}
    		
    		
   	 }
    	else
    	{
	  	colCb_->setItemText(idx,name);
		colCb_->setItemData(idx,realName);
		if(setCurrent)
		{
			// although we set the current index, this does not always trigger
			// slotCurrentChanged because all custom RGB values will have the
			// same index (42), even though they might be different colours
			// (which could be an issue if we open two different icons which both
			// have custom colours for the same parameter).
			// Therefore we manually trigger slotCurrentChanged here to make sure
			colCb_->setCurrentIndex(idx);
			slotCurrentChanged(idx);
		}
	}
	
	if(idx != -1)
	  	setColour(idx,color);	
}


void MvQColourLine::refresh(const vector<string>& values)
{
	if(values.size() > 0)
	{
		for(int i=0; i < colCb_->count(); i++)
		{
			if(colCb_->itemData(i).toString().toStdString() == values[0])
			{
			  	colCb_->setCurrentIndex(i);
				return;
			}	
		}
		
		QString name=QString::fromStdString(values[0]);
		//This sets the current index as well
		setCustomColour(MvQPalette::magics(values[0]),name,name,true);
	}
	
	//changed_ = false;
}

void MvQColourLine::slotCurrentChanged(int index)
{
	if(index >=0 && index < colCb_->count())
	{
	  	QString name=colCb_->itemData(index).toString();
		owner_.set(param_.name(),name.toStdString());
		if(!MvQPalette::isPseudo(name.toStdString()))
		{ 
			if(helper_ && helper_->widget())
			  	helper_->widget()->setEnabled(true);
			updateHelper();
		}
		else
		{
		  	if(helper_ && helper_->widget())
			  	helper_->widget()->setEnabled(false);
		}  
	}	
}

void MvQColourLine::slotHelperEdited(const vector<string>& values)
{
	if(values.size() > 0)
	{
	 	 for(int i=0; i < colCb_->count(); i++)
		{
			if(colCb_->itemData(i).toString().toStdString() == values[0])
			{
			  	colCb_->setCurrentIndex(i);
				return;
			}	
		}

		QString name=QString::fromStdString(values[0]);
		//This sets the current index as well
		setCustomColour(MvQPalette::magics(values[0]),name,name,true);
		
		//If the current index did not change the slotCurrentChanged() was
		//not called, so here we need to notify the owner about the change!!
		//if(colCb_->currentIndex() ==  currentPrev)
		//{
		//	owner_.set(param_.name(),name.toStdString());
		//}	
	}
}	

void MvQColourLine::updateHelper()
{
  	if(!helper_)
		return;
	
	int index=colCb_->currentIndex();
	
	vector<string> vals;	
	vals.push_back(colCb_->itemData(index).toString().toStdString());
	helper_->refresh(vals);
}  		

void MvQColourLine::slotHelperEditConfirmed()
{
	int index=colCb_->currentIndex();
	if(index != -1)
	{
	  	QString name=colCb_->itemData(index).toString();
		owner_.set(param_.name(),name.toStdString());  
	}	
}  

static LineMaker<MvQColourLine> maker1("colour");
