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

 Copyright 2013 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 "FamilyEditor.h"

#include <QComboBox>
#include <QDebug>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QScrollArea>
#include <QStackedWidget>
#include <QVBoxLayout>

#include "EditorFactory.h"
#include "FamilyScanner.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "IconObject.h"
//#include "Log.h"
#include "RequestPanel.h"

#include "MvQRequestPanelWidget.h"

FamilyEditor::FamilyEditor(const IconClass& name,const string& kind):
	MvQEditor(name,kind), 
	scanner_(FamilyScanner::find(name))
{
	QFrame *w=new QFrame(this);
	w->setFrameShape(QFrame::StyledPanel);
	//w->setProperty("mvStyle","familyCombo");
  
  	QHBoxLayout *hb=new QHBoxLayout(this);
	w->setLayout(hb);
	centralLayout_->addWidget(w);
	centralLayout_->addSpacing(4);
  
	comboLayout_=new QGridLayout;
	comboLayout_->setVerticalSpacing(4);
	comboLayout_->setHorizontalSpacing(4);
	comboLayout_->setContentsMargins(2,4,2,4);
	hb->addLayout(comboLayout_);
	hb->addStretch(1);
	
	//pages
	page_ = new QStackedWidget(this);
	centralLayout_->addWidget(page_);
	
	Request r(name.name().c_str());
	makePages(0,r);
		
	//Now we have all the combos defined we cand add signals-slots. 
	foreach(QComboBox *cb,combos_)
	{
		 connect(cb,SIGNAL(currentIndexChanged(int)),
        	         this, SLOT(slotChangePage(int)));	
	}		 
}

FamilyEditor::~FamilyEditor()
{
}

void FamilyEditor::setStartPage()
{
	if(!current_) return;
  
  	vector<string> keyValues;	
	const Request& r=current_->requestForVerb(class_.name());
	
	const vector<string>& p = scanner_.params();
	for(unsigned int i=0; i < p.size(); i++) 
	{
		const char* keyVal=r(p[i].c_str());
		if(keyVal)
		{  
			QString qsv(keyVal);
		  	for(int j=0;  j < combos_.at(i)->count(); j++)
			{
				if(combos_.at(i)->itemData(j,Qt::UserRole).toString() == qsv)
				{
				  	combos_.at(i)->setCurrentIndex(j);
				}
			}
		}
	}		
}	
	
void FamilyEditor::makePages(int n,Request& r)
{
	const vector<string>& p = scanner_.params();
	if(n >= static_cast<int>(p.size())) return;
	
	string paramName=p[n];
	
	const vector<string>& v = scanner_.values(paramName);
	const vector<string>& b = scanner_.beau(paramName);
	
	for(unsigned int i = 0; i < v.size(); i++)
	{
		r(paramName.c_str()) = v[i].c_str();

		if(combos_.count() < n+1)
		{
			int row=combos_.count();
			QLabel *lab=new QLabel("<b>"+QString::fromStdString(paramName) + ": </b>",this);
			QComboBox *combo=new QComboBox(this);
			comboLayout_->addWidget(lab,row,0);
			comboLayout_->addWidget(combo,row,1,Qt::AlignLeft);
			combos_ << combo;			
		}	
	
		QString name(b[i].c_str());
		
		if(combos_.at(n)->count() <  static_cast<int>(v.size()))
		{  
			QComboBox *combo=combos_.at(n);
			combo->addItem(name,QString::fromStdString(v[i]));
		}
	
		//Last keyword --> we create a panel
		if(n == static_cast<int>(p.size()) - 1)
		{						
			Request s = class_.language().expand(r);
			const char *type = s(scanner_.keyword().c_str());
		
			if(type)
			{					  		
			  	//Create panel
				vector<string> classes;
				classes.push_back(class_.name());
	
				MvQRequestPanelWidget *w=new MvQRequestPanelWidget(classes,this);
				RequestPanel *panel=new RequestPanel(IconClass::find(type), w, this,type);
				panels_.push_back(panel);
			
		 		QScrollArea *area=new QScrollArea(this);
				area->setWidgetResizable(true);			
				page_->addWidget(area);
				area->setWidget(w);
		
				connect(w,SIGNAL(iconDropped(IconObject*)),
		 			this,SLOT(slotIconDropped(IconObject*)));
					
			}
		}	
			
		makePages(n+1,r);
	}	  
}  


IconObject* FamilyEditor::copy(const string& /*name*/)
{
	//IconObject* o = IconFactory::create(name, class_);
	//panel_.apply();
	//o->request(panel_.request());
	//return o;
	return 0;
}


void FamilyEditor::apply()
{	
  	if(!current_) return;
  
  	Request r=current_->requestForVerb(class_.name());
	
	map<string,string> keyVals;
	keyValues(keyVals);
	for(map<string,string>::const_iterator it=keyVals.begin(); it != keyVals.end(); it++)
	{
		r(it->first.c_str())=it->second.c_str();
	}	
	
	int i=page_->currentIndex();
	if(i >= 0 &&  i < static_cast<int>(panels_.size()))
	{
	  	panels_.at(i)->apply();
		Request pr= panels_.at(i)->request();				
		r= r + panels_.at(i)->request();
		//r.print();		
		objects_.at(i)->request(pr);
	}
	
	current_->request(r);	
}

void FamilyEditor::edit()
{  
	if(!current_)
	  	return;
 
	objects_.clear();
  	
	for(unsigned int i=0; i < panels_.size(); i++)
	{  	
		const IconClass& kind=panels_.at(i)->iconClass();
			
		//Create icon object
		Request panelReq=current_->requestForVerb(kind.name());
		
		if(!panelReq)
			panelReq=Request(kind.name());
		
		panelReq.print();
		
		IconObjectH obj=IconFactory::createTemporary(current_,panelReq,&kind);
		objects_.push_back(obj);		
	}	
		
	MvQEditor::edit();
	
	setStartPage();
}

void FamilyEditor::reset()
{
	for(unsigned int i=0; i < panels_.size(); i++)
	{
	  	panels_.at(i)->reset(objects_.at(i));
	}	
}

void FamilyEditor::close()
{
	for(unsigned int i=0; i < panels_.size(); i++)
	{ 
		panels_.at(i)->close();
	}	
	objects_.clear();	
}

//Request FamilyEditor::currentRequest(long custom_expand)
//{
	//panel_.apply();
	//return custom_expand ? panel_.request(custom_expand) : panel_.request();
//}

void FamilyEditor::replace(IconObjectH /*o*/)
{
   	//panel_.replace(o);
}

void FamilyEditor::merge(IconObjectH /*o*/)
{
	//panel_.merge(o);
}


void  FamilyEditor::slotChangePage(int)
{
     	//Works only for two keywords (this is the maximum currently)!!!!
    
     	int index=0;
     	if(combos_.count() ==1)
     	{
   		index=combos_.at(0)->currentIndex();
	}
	else if(combos_.count() ==2)
	{
		index=combos_.at(0)->currentIndex();
		index*=combos_.at(1)->count();
		index+=combos_.at(1)->currentIndex();		
	}
     
     	page_->setCurrentIndex(index);
	
	MvQEditor::changed();
}
 
void  FamilyEditor::keyValues(map<string,string>& keyValues) 
{
	const vector<string>& p = scanner_.params();
	for(unsigned int i=0; i < p.size(); i++) 
	{
		string keyVal=p[i];	
		int index=combos_.at(i)->currentIndex();
		if(index > -1)
		{
			keyValues[keyVal]=combos_.at(i)->itemData(index,Qt::UserRole).toString().toStdString();
		}
	}	
}			
 
 
void FamilyEditor::slotIconDropped(IconObject* obj)
{	
	merge(obj);	 
}  


static EditorMaker<FamilyEditor> maker1("FamilyEditor");
