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

 Copyright 2012 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 <QDebug>
#include <QFile>
#include <QHBoxLayout>
#include <QPushButton>
#include <QStringList>
#include <QTextStream>

#include "MvQGui.h"
#include "MvQGuiItem.h"
#include "MvKeyProfile.h" 

#include "MvApplication.h"
#include "MvRequest.h"
#include "MvProtocol.h"

#ifdef METVIEW_ODB
#include "MvQOdbMetaData.h"
#endif

MvQGui::MvQGui(QBoxLayout* layout) : parentLayout_(layout)
{
	layout_ = new  QGridLayout;
	layout_->setSizeConstraint(QLayout::SetMinAndMaxSize);

	//okPb_ = new QPushButton("Ok");

	//connect(okPb_,SIGNAL(clicked()),
	//	this,SIGNAL(editFinished()));	
}

MvQGui::~MvQGui()
{
	clear();
	delete layout_;
	//delete okPb_;
}

void MvQGui::clear()
{
	//Remove layout from parent layout	
	parentLayout_->removeItem(layout_);

     	for(int i=0 ; i < layout_->rowCount(); i++)
	{
		for(int j=0; j< layout_->columnCount(); j++)
		{
			QLayoutItem *item= layout_->itemAtPosition(i,j);
             		layout_->removeItem(item);
		}
         }
        
	//Delete all the items (it will remove all the items 
	//from the layout)
	while(!item_.isEmpty())
     	{
		MvQGuiItem *item=item_.takeFirst();
		qDebug() << "name:" << item->name();
		delete item;
	}
	item_.clear();

	//Remove pb from the parent layout	
	parentLayout_->removeWidget(okPb_);	
}

/*void MvQGui::buildFromMacro(QString macroPath)
{

	//Clear the gui, we have to rebuild it
	clear();

	QFile file(macroPath); 
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        	return;

	QTextStream in(&file); 
	while (!in.atEnd()) 
	{
		QString line = in.readLine().simplified();
         	if(line.startsWith("#qt") == true)
		{
			QStringList list = line.split(QRegExp("\\s+"));

			QString keyName=list[1];
			QString name=list[2];
			QString type=list[4];
			QString source("grib");

			//Create hbox layout
			QHBoxLayout *hb=new  QHBoxLayout;
			layout_->addLayout(hb);

			//Create gui item
			MvQGuiItem *item=MvQGuiItemFactory::makeItem(name,type,hb);			

			item->setKeyName(list[1]);
			item->setName(list[2]);
		        item->setId(list[3]);
			item->setType(list[4]);
			item->setSource("grib");

			item_.push_back(item);
		}
	}

	okPb_=new QPushButton("Ok");
	layout_->addWidget(okPb_);

	connect(okPb_,SIGNAL(clicked()),
		this,SIGNAL(editFinished()));

}*/


void MvQGui::buildFromMacro(QString macroPath)
{	
	//Clear the gui, we have to rebuild it
	clear();

	//Build metview request to read gui definition
	//form the macro
	MvRequest r("MACROPARAM");
	
	MvRequest rr("MACRO");
	rr("PATH") = macroPath.toStdString().c_str();

	r("MACRO")=rr;
	r("_NAME")    = macroPath.toStdString().c_str();
	r("_CLASS")   = "MACROPARAM";
	r("_ACTION")  = "edit";
	r("_SERVICE") = "macro";
	//r.print();

	int error;
	MvRequest result = MvApplication::waitService("macro",r,error);
	//result.print();

	//layout_=new QGridLayout;
	layout_->setColumnMinimumWidth(2,40);
	layout_->setColumnMinimumWidth(3,150);
	parentLayout_->addLayout(layout_);

	//Build gui
	r=result.rewind();
	while(r)
	{
		qDebug() << "Gui item";
		r.print();

		//QHBoxLayout *hb=new  QHBoxLayout;
		//layout_->addLayout(hb);
		MvQGuiItem *item = MvQGuiItemFactory::makeItem(&r,layout_);
		if(item)
		{
			item_.push_back(item);
		}

		r.advance();
	}	

	//parentLayout_->addWidget(okPb_);
}

void MvQGui::buildFromDefinition(MvRequest& reqDef)
{
	layout_->setColumnMinimumWidth(2,40);
	layout_->setColumnMinimumWidth(3,150);
	parentLayout_->addLayout(layout_);

	//Build GUI
	while(reqDef)
	{
		qDebug() << "Gui item";
		reqDef.print();

		//QHBoxLayout *hb=new  QHBoxLayout;
		//layout_->addLayout(hb);
		MvQGuiItem *item = MvQGuiItemFactory::makeItem(&reqDef,layout_);
		if(item)
		{
			item_.push_back(item);
		}

		reqDef.advance();
	}	

	//parentLayout_->addWidget(okPb_);	
}

void MvQGui::buildFromKeyProfile(MvKeyProfile *prof)
{
	//Clear the gui, we have to rebuild it
	clear();
	
	layout_->setColumnMinimumWidth(2,40);
	layout_->setColumnMinimumWidth(3,150);
	parentLayout_->addLayout(layout_);

	for(unsigned int i=0; i < prof->size(); i++)
	{	
		//QString keyName=prof->at(i)->name().c_str();
		//QString name=prof->at(i)->shortName().c_str();
		
		MvRequest r("menu");
	
		r("name")    =  prof->at(i)->shortName().c_str() ;
		//r("default")   = "";
		r("source")  = prof->at(i)->name().c_str();
		
		//QHBoxLayout *hb=new  QHBoxLayout;
		//layout_->addLayout(hb);
		MvQGuiItem *item = MvQGuiItemFactory::makeItem(&r,layout_);
		if(item)
		{
			item_.push_back(item);
		}

		r.advance();
	}	

	//parentLayout_->addWidget(okPb_);

	update(prof);
}

void MvQGui::update(MvKeyProfile *prof)
{
	//Populate the gui with dynamic information 
	for(unsigned int i=0; i < item_.count(); i++)
	{
		MvQGuiItem *item=item_[i];
	
		qDebug() << "source: " << item->source();

		if(!item->source().isEmpty())
		{
			MvKey* key=prof->key(item->source().toStdString());
			if(key)
			{
				for(map<string,int>::iterator it=key->counter().begin(); 
                            	    it != key->counter().end(); it++)
				{
					item->addValue(it->first.c_str());
				}

			}
		}
	}
}

#ifdef METVIEW_ODB

void MvQGui::updateFromOdbMetaData(QList<MvQOdbColumn*>& col)
{
	//Populate the gui with dynamic information 
	for(unsigned int i=0; i < item_.count(); i++)
	{
		MvQGuiItem *item=item_[i];
	
		qDebug() << "source: " << item->source();

		if(!item->source().isEmpty())
		{
			foreach(MvQOdbColumn* c,col)
			{
				item->addValue(c->name());
			}
		}
	}
}

#endif