/***************************** 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 <QAction>
#include <QApplication>
#include <QBuffer>
#include <QCheckBox>
#include <QComboBox>
#include <QDebug>
#include <QFile>
#include <QGroupBox>
#include <QLabel>
#include <QListView>
#include <QListWidgetItem>
#include <QListWidget>
#include <QMenu>
#include <QMenuBar>
#include <QMovie>
#include <QProgressBar>
#include <QPushButton>
#include <QScrollArea>
#include <QSettings>
#include <QSplitter>
#include <QStatusBar>
#include <QStringListModel>
#include <QTextBrowser>
#include <QToolBar>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>

#include "MvQWcsClientEditor.h"

#include "LogHandler.h"

#include "MvQHighlighter.h"
#include "MvQLogBrowser.h"
#include "MvQOgcParam.h"
#include "MvQOgcRequest.h"
#include "MvQOgcTreeModel.h"
#include "MvQTextEditSearchLine.h"
#include "MvQWcsClient.h"

//================================
//
// MvQWcsClientEditor
//
//================================

MvQWcsClientEditor::MvQWcsClientEditor(MvQWcsUiClient *client, QWidget *parent) : MvQMainWindow(parent)
{
	//Window setup
	QString iconName;
	QStringList lst=client->iconFile().split("/");
	if(lst.count()>0)
	{
		iconName=lst.last();
	}

	//Initial size
	setInitialSize(1100,800);

	setAttribute(Qt::WA_DeleteOnClose);
	setWindowTitle("Metview - WCS Client Editor- " + iconName);

	client_ = client;

	//ClientModeMap	
	clientModeMap_["Plain"]=MvQWcsUiClient::BasicMode;
	clientModeMap_["Interactive"]=MvQWcsUiClient::AdvancedMode;

	//Main layout
	mainLayout_=new QVBoxLayout;
	QWidget *w=new QWidget;
	w->setLayout(mainLayout_);
	setCentralWidget(w);

	//Main splitter
	mainSplitter_= new QSplitter;
	mainSplitter_->setOrientation(Qt::Vertical);
        mainSplitter_->setOpaqueResize(false);
	mainLayout_->addWidget(mainSplitter_);	

	//----------------------------------------------
	// Request splitter  - upper part of main splitter
	//----------------------------------------------

	requestSplitter_= new QSplitter;
        requestSplitter_->setOpaqueResize(false);
	mainSplitter_->addWidget(requestSplitter_);	

	//Request left layout
	layerPanel_=new QWidget;
	QVBoxLayout* requestLeftLayout=new QVBoxLayout;
	layerPanel_->setLayout(requestLeftLayout);
	requestSplitter_->addWidget(layerPanel_);

	//Request right layout
	layerInfoTab_=new QTabWidget;
	requestSplitter_->addWidget(layerInfoTab_);
	
	requestSplitter_->setCollapsible(0,false);
	requestSplitter_->setCollapsible(1,false);

	//----------------------------------------------
	// Log area - lower part of main splitter
	//----------------------------------------------

	QVBoxLayout *logLayout = new QVBoxLayout;
        logLayout->setObjectName(QString::fromUtf8("vboxLayout"));
	logLayout->setContentsMargins(0,0,0,0);

	logPanel_=new QWidget;
	logPanel_->setMinimumHeight(110);
	logPanel_->setLayout(logLayout);

	QHBoxLayout *hb = new QHBoxLayout;
	hb->setContentsMargins(0,0,0,0);
	logLayout->addLayout(hb);

	//Label
	QLabel *label = new QLabel(tr("Log"));
	label->setFrameShape(QFrame::StyledPanel);
	hb->addWidget(label,1);

	//Clear button
	QPushButton *clearPb = new QPushButton(tr("Clear log"));
	hb->addWidget(clearPb);

	//Log browser
	logBrowser_= new MvQLogBrowser(logLayout);

	connect(clearPb,SIGNAL(clicked(bool)),
		this,SLOT(slotClearLog(bool)));

	mainSplitter_->addWidget(logPanel_);
	mainSplitter_->setCollapsible(1,false);

	//---------------------------------------
	// Bottom part with buttons	
	//---------------------------------------

	//Buttons
	hb=new QHBoxLayout;
	mainLayout_->addLayout(hb);

	QLabel *labelMode= new QLabel(tr("Mode:"),this);
	clientModeCombo_ = new QComboBox(this);
	clientModeCombo_->addItem("Plain");
	clientModeCombo_->addItem("Interactive");
	hb->addWidget(labelMode);
	hb->addWidget(clientModeCombo_);
	hb->addStretch(1);

	if(client_->clientMode() ==MvQWcsUiClient::AdvancedMode)
	{
		clientModeCombo_->setCurrentIndex(1);
	}
	else
	{
		clientModeCombo_->setCurrentIndex(0);
	}	

	label=new QLabel(tr("Stay open"));
	openCb_ = new QCheckBox;
	openCb_->setCheckState(Qt::Unchecked);
	hb->addWidget(openCb_);
	hb->addWidget(label);

	QPushButton *okPb = new QPushButton("Apply");
	okPb->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogOkButton)); 
	hb->addWidget(okPb);

	QPushButton *closePb = new QPushButton("Close");
	closePb->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCloseButton)); 
	hb->addWidget(closePb);

	//-------------------
	// Statusbar
	//-------------------

	/*loadLabel_ = new QLabel;
	QMovie *movie = new QMovie(":/OgcClient/loader.gif", QByteArray(), loadLabel_);
	loadLabel_->setMovie(movie);
	statusBar()->addPermanentWidget(loadLabel_);
	loadLabel_->hide();*/

	loadProgress_=new QProgressBar;
	//loadProgress_->setRange(0,0);
	statusBar()->addPermanentWidget(loadProgress_);
	loadProgress_->hide();
	
 	statusMessageLabel_ = new QLabel("");
    	//statusMessageLabel_->setTextInteractionFlags(Qt::TextSelectableByMouse);
    	statusMessageLabel_->setFrameShape(QFrame::NoFrame);
	//messageLabel_->setMinimumSize(messageLabel_->sizeHint());
    	statusBar()->addPermanentWidget(statusMessageLabel_,1);  // '1' means 'please stretch me when resized'

	//-------------
	// Init
	//-------------

	//Menu and toolbar actions
	setupControlsActions();
	setupViewActions();

	// Setup menus and toolbars
	setupMenus(menuItems_);
		
	//Request panel
	setupLayerPanel(requestLeftLayout);
	setupLayerInfoTab();

	dimensionNum_=0;

	//Signals and slots
	connect(okPb,SIGNAL(clicked()),
		this,SLOT(slotSaveInfo()));

	connect(openCb_,SIGNAL(stateChanged(int)),
		this,SLOT(slotStayOpen(int)));

	connect(closePb,SIGNAL(clicked()),
		this,SLOT(close()));

	connect(clientModeCombo_,SIGNAL(currentIndexChanged(QString)),
		this,SLOT(slotClientModeChanged(QString)));

	connect(client_,SIGNAL(statusMessage(QString)),
		this,SLOT(slotStatusMessage(QString)));
		
	connect(client_,SIGNAL(getCapLoaded()),
		this,SLOT(slotGetCapabilityLoaded()));

	connect(client_,SIGNAL(describeCovLoaded()),
		this,SLOT(slotDescribeCovLoaded()));

	connect(client_,SIGNAL(logUpdated()),
		this,SLOT(slotUpdateLogOutput()));


	//Initialise the current mode --> call loadGetCapabilities
	//This must come last!!!
	initClientMode();

	//
	readSettings();
}	

MvQWcsClientEditor::~MvQWcsClientEditor()
{	
	writeSettings();
}

void MvQWcsClientEditor::setupControlsActions()
{
	//---------------------
	// First toolbar row
	//---------------------

	actionCapability_ = new QAction(this);
        actionCapability_->setObjectName(QString::fromUtf8("actionCapability"));
	actionCapability_->setText(tr("&Load GetCapabilities"));
	actionCapability_->setToolTip(tr("Load GetCapabilities"));
	QIcon icon;
	icon.addPixmap(QPixmap(QString::fromUtf8(":/OgcClient/reload.png")), QIcon::Normal, QIcon::Off);
 	actionCapability_->setIcon(icon);	

	actionStopLoad_ = new QAction(this);
        actionStopLoad_->setObjectName(QString::fromUtf8("actionStopLoad"));
	actionStopLoad_->setText(tr("&Stop load process"));
	actionStopLoad_->setToolTip(tr("Stop load process"));
	QIcon icon1;
	icon1.addPixmap(QPixmap(QString::fromUtf8(":/OgcClient/stop_load.png")), QIcon::Normal, QIcon::Off);
 	actionStopLoad_->setIcon(icon1);	

	urlCombo_ = new QComboBox;
	urlCombo_->setEditable(true);
	urlCombo_->setMinimumContentsLength(20);
	//urlCombo_->setMaxCount(20);
	QSizePolicy p=urlCombo_->sizePolicy();
	urlCombo_->setSizePolicy(QSizePolicy::Expanding,p.verticalPolicy()); 
	urlCombo_->setInsertPolicy(QComboBox::InsertAtTop);

	//Server version combo
	QLabel *labelVersion= new QLabel(tr(" Version:"));
	versionCombo_ = new QComboBox;
	toolBarLabel_ << labelVersion;

	QStringList lst;
	lst << "Default" << "1.0.0" << "1.1" ;
	versionCombo_->addItems(lst);
	versionCombo_->setCurrentIndex(0);
	
	//---> Init
	
	//Init  url and version combos
	if(!client_->url().isEmpty())
	{	
		urlCombo_->insertItem(0,client_->url());
		urlCombo_->setCurrentIndex(0);
	}

	initVersionCombo();


	//---> Signals and slots

	connect(actionCapability_,SIGNAL(triggered()),
		this,SLOT(slotRunGetCapabilities()));

	connect(actionStopLoad_,SIGNAL(triggered()),
		client_,SLOT(slotAbortDownloadProcess()));

	connect(urlCombo_,SIGNAL(activated(QString)),
		this,SLOT(slotSelectUrl(QString)));

	connect(urlCombo_->lineEdit(),SIGNAL(editingFinished()),
		this,SLOT(slotCheckUrlComboContents()));

	connect(versionCombo_,SIGNAL(activated(QString)),
		this,SLOT(slotSelectVersion(QString)));

	MvQMainWindow::MenuType menuType=MvQMainWindow::ToolsMenu;
	menuItems_[menuType].push_back(new MvQMenuItem(actionCapability_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionStopLoad_));	
	menuItems_[menuType].push_back(new MvQMenuItem(urlCombo_,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(labelVersion,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(versionCombo_,MvQMenuItem::ToolBarTarget));

	//---------------------
	// Second toolbar row
	//--------------------

	QLabel *labelFormat= new QLabel(tr("Format:"));
	formatCombo_= new QComboBox;
	formatCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
	toolBarLabel_ << labelFormat;

	//Extra getcap
	QLabel *labelGetCap= new QLabel(tr(" Extra getCap param:"));
	extraGetCapEdit_= new QLineEdit("");	
	toolBarLabel_ << labelGetCap;

	//Extra getcov
	QLabel *labelGetCov= new QLabel(tr(" Extra getCov param:"));
	extraGetCovEdit_= new QLineEdit("");	
	toolBarLabel_ << labelGetCov;

	QString mName="Format";

	//Put this toolbar into another line!!!
	//addToolBarBreak(Qt::TopToolBarArea);

	menuType=MvQMainWindow::EditMenu;
	menuItems_[menuType].push_back(new MvQMenuItem(labelFormat,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(formatCombo_,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(labelGetCap,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(extraGetCapEdit_,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(labelGetCov,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(extraGetCovEdit_,MvQMenuItem::ToolBarTarget));	


	//These are independent from getCapabilities
	initExtraParEdit();

	connect(formatCombo_,SIGNAL(activated(QString)),
		client_,SLOT(slotSetFormatFromDpy(QString)));

	connect(extraGetCapEdit_,SIGNAL(textChanged(QString)),
		this,SLOT(slotExtraGetCapChanged(QString)));

	connect(extraGetCovEdit_,SIGNAL(textChanged(QString)),
		this,SLOT(slotExtraGetCovChanged(QString)));
}


void MvQWcsClientEditor::setupViewActions()
{
	//
	actionLog_ = new QAction(this);
        actionLog_->setObjectName(QString::fromUtf8("actionLog"));
	actionLog_->setText(tr("&Log"));
	actionLog_->setCheckable(true);
	actionLog_->setChecked(false);
	actionLog_->setToolTip(tr("View log"));
	QIcon icon1;
	icon1.addPixmap(QPixmap(QString::fromUtf8(":/examiner/log.png")), QIcon::Normal, QIcon::Off);
 	actionLog_->setIcon(icon1);	

	logPanel_->hide();

	//Define routines
	connect(actionLog_,SIGNAL(toggled(bool)),
		logPanel_,SLOT(setVisible(bool)));

	MvQMainWindow::MenuType menuType=MvQMainWindow::ViewMenu;
	menuItems_[menuType].push_back(new MvQMenuItem(actionLog_));
}


void MvQWcsClientEditor::setupLayerPanel(QVBoxLayout *layout)
{
	QLabel *label;
	QVBoxLayout *vb;
	QHBoxLayout *hb;
	int row=0;

	layerParamRowNum_=0;

	//Tab
	layerTab_=new QTabWidget;
	layout->addWidget(layerTab_);


	//layerSplitter_= new QSplitter;
	//layerSplitter_->setOrientation(Qt::Vertical);
        //layerSplitter_->setOpaqueResize(false);
	//layout->addWidget(layerSplitter_);	

	//--------------------------
	// Layer tree
	//--------------------------

	layerTree_=new QTreeView;
	layerTree_->setObjectName("WcsLayerTree");
	layerTree_->setProperty("mvStyle",1);
	layerTree_->setAlternatingRowColors(true);
	//layerSplitter_->addWidget(layerTree_);

	layerModel_=new MvQOgcTreeModel;
	layerTree_->setModel(layerModel_);

	connect(layerTree_,SIGNAL(clicked(QModelIndex)),
		this,SLOT(slotSelectLayer(QModelIndex)));

	connect(layerTree_,SIGNAL(activated(QModelIndex)),
		this,SLOT(slotSelectLayer(QModelIndex)));

	layerTab_->addTab(layerTree_,tr("Layer tree"));

	//--------------------------
	// Coverage offering list
	//--------------------------

	covOfferList_= new QListView;
	covOfferList_->setObjectName("WcsCovOfferList");
	covOfferList_->setProperty("mvStyle",1);
	covOfferList_->setAlternatingRowColors(true);

	covOfferModel_=new QStringListModel;
	covOfferList_->setModel(covOfferModel_);

	//connect(covOfferList_,SIGNAL(clicked(QModelIndex)),
	//	this,SLOT(slotSelectLayer(QModelIndex)));

	//connect(covOfferList_,SIGNAL(activated(QModelIndex)),
	//	this,SLOT(slotSelectLayer(QModelIndex)));

	layerTab_->addTab(covOfferList_,tr("Coverage Offer"));

	

	//-------------------
	// Param gui
	//-------------------

	QScrollArea *scroll = new QScrollArea;
	layerTab_->addTab(scroll,tr("Layer settings"));

	QWidget *w=new QWidget;
	layerGrid_= new QGridLayout;
	layerGrid_->setSizeConstraint(QLayout::SetMinAndMaxSize);
	w->setLayout(layerGrid_);

	scroll->setWidgetResizable(true);
	scroll->setWidget(w);

	label= new QLabel("Styles:");
	styleCombo_ = new QComboBox;
	layerGrid_->addWidget(label, row, 0);
	layerGrid_->addWidget(styleCombo_, row, 2);
	row++;

	label= new QLabel("CRS:");
	crsCombo_ = new QComboBox;
	layerGrid_->addWidget(label, row, 0);
	layerGrid_->addWidget(crsCombo_, row, 2);
	row++;
	
	layerParamRowNum_=row;

	//layerGrid_->setColumnStretch(1,1);
	//layerGrid_->setRowStretch(row,1);

	connect(crsCombo_,SIGNAL(activated(QString)),
		this,SLOT(slotSelectCrs(QString)));

	connect(styleCombo_,SIGNAL(activated(int)),
		this,SLOT(slotSelectStyle(int)));


	//Preview pb
	describeCovPb_ = new QPushButton(tr("Run describe coverage"));
	layout->addWidget(describeCovPb_);

	connect(describeCovPb_,SIGNAL(clicked()),
		this,SLOT(slotRunDescribeCov()));
}

void MvQWcsClientEditor::setupLayerInfoTab()
{
	QLabel *label;
	QWidget *w;

	//Read css for the preview formatting
	QString cssDoc;
	QFile f(":/OgcClient/preview.css");
	QTextStream in(&f);
	if(f.open(QIODevice::ReadOnly | QIODevice::Text))
	{
       		cssDoc=QString(f.readAll());
	}
	f.close();

	layerPreview_ = new QTextBrowser;
	layerPreview_->setReadOnly(true);
	layerPreview_->document()->setDefaultStyleSheet(cssDoc);

	layerInfoTab_->addTab(layerPreview_,tr("Layer information"));	

	connect(client_,SIGNAL(previewLoaded(QString)),
		this,SLOT(slotPreviewLoaded(QString)));

	connect(client_,SIGNAL(legendLoaded(QString)),
		this,SLOT(slotLegendLoaded(QString)));

	//GetCov request info
	w= new QWidget;
	QVBoxLayout *mapInfoLayout=new QVBoxLayout;
	w->setLayout(mapInfoLayout);
	layerInfoTab_->addTab(w,tr("GetCoverage request"));

	label=new QLabel(tr("Metview request:"));
	mapInfoLayout->addWidget(label);

	getCovInfoMv_ = new QTextBrowser;
	getCovInfoMv_->setReadOnly(true);
	//getCovInfoMv_->setLineWrapMode(QTextEdit::NoWrap);
	mapInfoLayout->addWidget(getCovInfoMv_);

	/*QString s="Individual requests (maximum ";
	s+=QString::number(MvQGetMapRequest::maxStep()) + "):";
	label=new QLabel(tr(s.toStdString().c_str()));
	mapInfoLayout->addWidget(label);

	getMapInfoSplit_ = new QTextBrowser;
	getMapInfoSplit_->setReadOnly(true);
	getMapInfoSplit_->document()->setDefaultStyleSheet(cssDoc);
	//getMapInfoSplit_->setLineWrapMode(QTextEdit::NoWrap);
	mapInfoLayout->addWidget(getMapInfoSplit_,1);*/

	highlighterMv_ = new MvQHighlighter(getCovInfoMv_->document());
	//highlighterSplit_ = new MvQHighlighter(getMapInfoSplit_->document());

	//slotSetGetMapInfo(client_->getMapRequest()->requestStep());

	//connect(getCovInfoMv_,SIGNAL(textChanged()),
	//	this,SLOT(slotGetMapChanged()));

	connect(client_,SIGNAL(getCovRequestChanged(QString)),
		this,SLOT(slotSetGetCovInfo(QString)));

	//GetCapabilities info
	w=new QWidget;
	QVBoxLayout *getCapLayout = new QVBoxLayout;
	w->setLayout(getCapLayout);

	getCapInfo_ = new QTextBrowser;
	getCapInfo_->setReadOnly(true);
	getCapInfo_->setLineWrapMode(QTextEdit::NoWrap);
	getCapLayout->addWidget(getCapInfo_);

	getCapSearch_= new MvQTextEditSearchLine(getCapInfo_,tr("Find:"));
	getCapLayout->addWidget(getCapSearch_);

	layerInfoTab_->addTab(w,tr("GetCapabilities"));
	
	highlighterGetCap_ = new MvQWmsGetCapHighlighter(getCapInfo_->document());

	//CoverageDescriptions
	w=new QWidget;
	QVBoxLayout *descCovLayout = new QVBoxLayout;
	w->setLayout(descCovLayout);

	describeCovInfo_ = new QTextBrowser;
	describeCovInfo_->setReadOnly(true);
	describeCovInfo_->setLineWrapMode(QTextEdit::NoWrap);
	descCovLayout->addWidget(describeCovInfo_);

	describeCovSearch_= new MvQTextEditSearchLine(describeCovInfo_,tr("Find:"));
	descCovLayout->addWidget(describeCovSearch_);

	layerInfoTab_->addTab(w,tr("DescribeCoverage"));
	
	highlighterDescribeCov_ = new MvQWmsGetCapHighlighter(describeCovInfo_->document());

	//Service matadata
	serviceInfo_ = new QTextBrowser;
	serviceInfo_->setReadOnly(true);
	serviceInfo_->document()->setDefaultStyleSheet(cssDoc);
	serviceInfo_->setWordWrapMode(QTextOption::WordWrap);

	layerInfoTab_->addTab(serviceInfo_,tr("Service"));

	//MvQHighlighter *highlighter = new MvQHighlighter(getMapInfo_->document());
	//slotSetGetMapInfo(client_->getMapRequest()->requestStep());

}

//-------------------------------
//
// Init
//
//-------------------------------

void MvQWcsClientEditor::initVersionCombo()
{
	QString currentVersion=client_->version();

	for(int i =0; i < versionCombo_->count(); i++)
	{
		if(currentVersion == versionCombo_->itemText(i))
		{
			versionCombo_->setCurrentIndex(i);
		}
	}
	
}	

void MvQWcsClientEditor::clearServerDependentData()
{
	formatCombo_->clear();
	
	clearLayerDependentData();
	getCovInfoMv_->clear();	
}

void MvQWcsClientEditor::clearLayerDependentData()
{
	layerModel_->dataIsAboutToChange();
	layerModel_->setRootNode(0); 

	styleCombo_->clear();
	crsCombo_->clear();
	clearDimension();
}

void MvQWcsClientEditor::clearDimension()
{
	int row=layerParamRowNum_; //layerGrid_->rowCount();
	row=row-1;

	qDebug() << "rows" << layerParamRowNum_ << layerGrid_->rowCount();

	//Remove previous dimension widgets from the grid
	for(unsigned int i=0; i < dimensionNum_;i++)
	{
		QWidget *w;

		w=layerGrid_->itemAtPosition(row,2)->widget();
		layerGrid_->removeWidget(w);
		row--;

		w=layerGrid_->itemAtPosition(row,0)->widget();
		layerGrid_->removeWidget(w);

		w=layerGrid_->itemAtPosition(row,1)->widget();
		layerGrid_->removeWidget(w);

		w=layerGrid_->itemAtPosition(row,2)->widget();
		layerGrid_->removeWidget(w);

		w=layerGrid_->itemAtPosition(row,3)->widget();
		layerGrid_->removeWidget(w);

		row--;

		layerParamRowNum_-=2;
	} 

	dimensionNum_=0;

	/*QMapIterator<QString, MvQWmsDimensionGuiItem*> it(dim_);
   	while (it.hasNext()) 
     	{ 
       		it.next();
       		delete it.value();
	}
	dim_.clear();*/
}

void MvQWcsClientEditor::initFormatCombo()
{
	formatCombo_->clear();

	QStringList values=client_->formatDisplayValues();

	for(int i=0; i < values.count(); i++)
	{
		formatCombo_->addItem(values[i]);
		if(!client_->supportedMimeType().contains(values[i]))
		{
			formatCombo_->setItemData(i,Qt::darkGray,Qt::ForegroundRole);
			formatCombo_->setItemData(i,tr("Not supported by Metview"),Qt::ToolTipRole);
		}
	}
	
	QString cv=client_->formatCurrentDisplayValue();	
	int index=-1;
	if(!cv.isEmpty())
	{
		index=values.indexOf(cv);
	}
	else
	{
		index=values.indexOf("image/png");
		if(index == -1 && values.count() > 0)
		{
			index=0;
		}
	}	

	if(index >=0)
	{
		formatCombo_->setCurrentIndex(index);
		client_->slotSetFormatFromDpy(values[index]);
	}
}


void MvQWcsClientEditor::initExtraParEdit()
{
	QString value=client_->extraGetCapPar();
	extraGetCapEdit_->setText(value);

	value=client_->extraGetCovPar();
	extraGetCovEdit_->setText(value);
}	

void MvQWcsClientEditor::setupLayerList()
{
	layerModel_->dataIsAboutToChange();
	layerModel_->setRootNode(client_->layer()->root());

	layerTree_->setCurrentIndex(layerModel_->indexFromNode(client_->layer()->currentNode()));

/*	layerList_->clear();

	QStringList values=client_->layerDisplayValues();
	QStringList desc=client_->layerDescriptions();

	int i=0;
	foreach(QString str, values)
	{		
		QListWidgetItem* item=new QListWidgetItem(str,layerList_);
		item->setData(Qt::ToolTipRole,desc[i]);
		i++;
	}

	int index=client_->layerCurrentIndex();		
	if(index > -1)
	{
		layerList_->setCurrentRow(index);
	}*/
}

void MvQWcsClientEditor::setupCovOfferList()
{
	QList<MvQOgcElem*> elems=client_->covOffer();
	QStringList vals;
	foreach(MvQOgcElem* e,elems)
	{
		vals << e->attribute("Title");
	}

	covOfferModel_->setStringList(vals);
	

/*	layerList_->clear();

	QStringList values=client_->layerDisplayValues();
	QStringList desc=client_->layerDescriptions();

	int i=0;
	foreach(QString str, values)
	{		
		QListWidgetItem* item=new QListWidgetItem(str,layerList_);
		item->setData(Qt::ToolTipRole,desc[i]);
		i++;
	}

	int index=client_->layerCurrentIndex();		
	if(index > -1)
	{
		layerList_->setCurrentRow(index);
	}*/
}
void MvQWcsClientEditor::initStyleCombo()
{
	styleCombo_->clear();

	QStringList values=client_->styleDisplayValues();
	QStringList desc=client_->styleDescriptions();

	int i=0;
	foreach(QString str, values)
	{
		styleCombo_->addItem(str);
		styleCombo_->setItemData(i,desc[i],Qt::ToolTipRole);
		i++;
	}

	int index=client_->styleCurrentIndex();	
	if(index == -1 && values.count() > 0)
	{
		index=0;
	}
	if(index >=0)
	{
		styleCombo_->setCurrentIndex(index);
		client_->setStyleCurrentIndex(index);
	}
}

void MvQWcsClientEditor::initCrsCombo()
{
	crsCombo_->clear();

	QStringList values=client_->crsDisplayValues();

	for(int i=0; i < values.count(); i++)
	{
		crsCombo_->addItem(values[i]);
		if(!client_->supportedCrs().contains(values[i]))
		{
			crsCombo_->setItemData(i,Qt::darkGray,Qt::ForegroundRole);
			crsCombo_->setItemData(i,tr("Not supported by Metview"),Qt::ToolTipRole);
		}
	}

	QString cv=client_->crsCurrentDisplayValue();	
	int index=-1;

	qDebug() << cv;
	qDebug() << values;
	if(!cv.isEmpty())
	{
		index=values.indexOf(cv);
	}
	else
	{
		foreach(QString str, values)
		{
			if(str.contains("EPSG:4326"))
			{
				index=values.indexOf(str);
				break;
			}
		}	
		if(index == -1 && values.count() > 0)
		{
			index=0;
		}
	}

	if(index >=0)
	{
		crsCombo_->setCurrentIndex(index);
		client_->setCrsCurrentDisplayValue(values[index]);
	}
}

void MvQWcsClientEditor::setupDimension()
{
	/*clearDimension();


	foreach(MvQOgcDimension *dim,client_->dimension())
	{
		QString name=dim->displayName();
		dim_[name]=new MvQWmsDimensionGuiItem(dim,dim->currentValues(),layerGrid_,layerParamRowNum_);

		connect(dim_[name],SIGNAL(textChanged(MvQOgcDimension*,QString)),
			this,SLOT(slotDimensionChanged(MvQOgcDimension*,QString)));
	
		dimensionNum_++;
		layerParamRowNum_+=2;
	}*/
}


//------------------------------------------
//
//  SLOTS
//
//------------------------------------------

void MvQWcsClientEditor::slotSelectUrl(const QString &url)
{
	client_->setUrl(url,versionCombo_->currentText());
	clearServerDependentData();
}

void MvQWcsClientEditor::slotSelectVersion(const QString &version)
{
	if(version.compare(client_->version(),Qt::CaseInsensitive) != 0)
	{
		client_->setVersion(version);
		slotRunGetCapabilities();
	}
}

void MvQWcsClientEditor::slotRunGetCapabilities()
{	
	if(client_->url().isEmpty())
		return;

	layerModel_->dataIsAboutToChange();
	layerModel_->setRootNode(0);

	requestSplitter_->setEnabled(false);

	actionCapability_->setEnabled(false);
	actionStopLoad_->setEnabled(true);
	requestSplitter_->widget(0)->setEnabled(false);
	urlCombo_->setEnabled(false);
	versionCombo_->setEnabled(false);
	formatCombo_->setEnabled(false);
	clientModeCombo_->setEnabled(false);

	loadStarted();

	client_->slotRunGetCap();
}

void MvQWcsClientEditor::slotGetCapabilityLoaded()
{	
	requestSplitter_->setEnabled(true);

	actionCapability_->setEnabled(true);
	actionStopLoad_->setEnabled(false);
	requestSplitter_->widget(0)->setEnabled(true);
	urlCombo_->setEnabled(true);
	versionCombo_->setEnabled(true);
	formatCombo_->setEnabled(true);
	clientModeCombo_->setEnabled(true);

	initFormatCombo();
	setupCovOfferList();

	initStyleCombo();
	initCrsCombo();
	setupDimension();

	slotPreviewLoaded(QString());

	getCapInfo_->setPlainText(client_->getCapDoc());
	slotUpdateServiceInfo(); 

	loadFinished();
}

void MvQWcsClientEditor::slotSelectLayer(const QModelIndex& index)
{
	MvQOgcNode *node=layerModel_->nodeFromIndex(index);
	client_->setLayerFromDpy(node);

	initStyleCombo();
	initCrsCombo();
	setupDimension();

	slotPreviewLoaded(QString());
}

void MvQWcsClientEditor::slotDimensionChanged(MvQOgcDimension* dim,QString val)
{
	if(dim)
	{	
		client_->setDimensionFromDpy(dim->displayName(),val);
	}
}

void MvQWcsClientEditor::slotExtraGetCapChanged(QString val)
{
	client_->setExtraGetCapPar(val);
}

void MvQWcsClientEditor::slotExtraGetCovChanged(QString val)
{
	client_->setExtraGetCovPar(val);
}

void MvQWcsClientEditor::slotAddItemToUrlCombo(QString s)
{
	qDebug() << s;
	return;


	while(urlCombo_->count() >=  urlCombo_->maxCount()-1)
	{
		urlCombo_->removeItem(urlCombo_->count()-1);
	}

	urlCombo_->insertItem(0,urlCombo_->lineEdit()->text());
}

void MvQWcsClientEditor::slotPreview()
{
	//previewPb_->setEnabled(false);
	/*actionCapability_->setEnabled(false);
	actionStopLoad_->setEnabled(true);
	requestSplitter_->widget(0)->setEnabled(false);
	clientModeCombo_->setEnabled(false);

	loadStarted();

	client_->downloadPreview();*/
}

void MvQWcsClientEditor::slotRunDescribeCov()
{
	//previewPb_->setEnabled(false);
	actionCapability_->setEnabled(false);
	actionStopLoad_->setEnabled(true);
	requestSplitter_->widget(0)->setEnabled(false);
	clientModeCombo_->setEnabled(false);

	loadStarted();

	client_->slotRunDescribeCov();
}

void MvQWcsClientEditor::slotDescribeCovLoaded()
{
	describeCovInfo_->setPlainText(client_->describeCovDoc());
	loadFinished();
}


void MvQWcsClientEditor::slotPreviewLoaded(QString previewPath)
{
	QString layerText=client_->layerAbstract();
	layerText.replace("\n","<br>");

	QString  s="<table><tbody>";	
	s+="<tr><td class=\"first\">Title</td><td>"+ client_->layerTitle() +"</td></tr>";
	s+="<tr><td class=\"first\">Name</td><td>"+ client_->layerName() +"</td></tr>";
	s+="<tr><td class=\"first\">Abstract</td><td>"+ layerText +"</td></tr>";
	s+="<tr><td class=\"first\">CRS</td><td>"+ crsCombo_->currentText() +"</td></tr>";
	s+="<tr><td class=\"first\">Style</td><td>"+ styleCombo_->currentText() +"</td></tr>";
	
	/*s+="<tr><td class=\"first\">Dimensions</td>";
	QMapIterator<QString,MvQWmsDimensionGuiItem*> it(dim_);
	s+="<td>";
	while (it.hasNext()) 
	{
    		it.next();
		s+=it.key() + " = " + it.value()->currentValue() + "<br>";		
	}
	s+="</td></tr>";*/

	s+="<tr><td class=\"first\">Preview</td>";
	if(previewPath.isEmpty() == false)
	{
		s+="<td align=center><img src=" + previewPath + "></td>";
	}
	else
	{
		s+="<td align=center></td>";
	}
	s+="</tr>";
	s+="<tr><td class=\"first\">Legend</td>";
	s+="<td class=\"image\" align=center>Legend not loaded</td></tr>";
	s+="</tbody></table>";


	layerPreview_->setHtml(s);

	//previewPb_->setEnabled(true);
	//actionCapability_->setEnabled(true);
	//actionStopLoad_->setEnabled(false);
	//requestSplitter_->widget(0)->setEnabled(true);

	if(previewPath.isEmpty())
	{	
		slotLegendLoaded(QString());
		return;
	}
	//
	client_->downloadLegend();	
}

void MvQWcsClientEditor::slotLegendLoaded(QString legendPath)
{
	QString txt=layerPreview_->toHtml();
	
	if(!legendPath.isEmpty())	
	{
		QString s="<img src=\"" + legendPath + "\">";
		txt.replace("Legend not loaded",s);
		layerPreview_->setHtml(txt);
	}

	//previewPb_->setEnabled(true);
	actionCapability_->setEnabled(true);
	actionStopLoad_->setEnabled(false);
	requestSplitter_->widget(0)->setEnabled(true);
	clientModeCombo_->setEnabled(true);

	loadFinished();
}

void MvQWcsClientEditor::slotUpdateLogOutput()
{
	logBrowser_->update();
}

void MvQWcsClientEditor::slotClearLog(bool)
{
	LogHandler::instance()->clear();
	logBrowser_->clear();
}

void MvQWcsClientEditor::slotSelectStyle(int index)
{
	client_->setStyleCurrentIndex(index);
}

void MvQWcsClientEditor::slotSelectCrs(QString value)
{
	client_->setCrsCurrentDisplayValue(value);
}

void MvQWcsClientEditor::slotCheckUrlComboContents()
{
	qDebug() << "slotCheckUrlComboContents called";

	int maxCount=25;

	/*QStringList lst;
	for(int i=0; i < urlCombo_->count(); i++)
	{
		lst << urlCombo_->itemText(i);
	}

	lst.removeDuplicates();*/

	for(int i=urlCombo_->count()-1; i > maxCount; i--)
	{
		urlCombo_->removeItem(i);
	}
}

void MvQWcsClientEditor::slotSetGetCovInfo(QString req)
{
	if(client_->clientMode() == MvQWcsUiClient::AdvancedMode)
	{
		getCovInfoMv_->setPlainText(req);
	}
}

void MvQWcsClientEditor::slotGetCovChanged()
{	
	client_->setGetCovRequest(getCovInfoMv_->toPlainText());
}

void MvQWcsClientEditor::slotUpdateServiceInfo()
{
	QMap<QString,QString> meta=client_->serviceMetaData();

	QString  s="<table><tbody>";

	//s+="<tr><td class=\"first\">Title</td><td>"+ meta["Title"] +"</td></tr>";
	//s+="<tr><td class=\"first\">Abstract</td><td>"+ meta["Abstract"] +"</td></tr>";
	
	QStringList contact;
	contact << "name" << "description" << "label" << 
				"fees" << "accessConstraints";


	foreach(QString t,contact)
	{
		if(!meta[t].isEmpty())
		{
			s+="<tr><td class=\"first\">" + t + "</td><td>"+ client_->serviceMetaData()[t] +"</td></tr>";	
		}
	}
	
	s+="</tbody></table>";

	serviceInfo_->setHtml(s);
}

void MvQWcsClientEditor::initClientMode()
{	
	if(client_->clientMode() == MvQWcsUiClient::BasicMode)
	{
		layerPanel_->hide();
		clearLayerDependentData();

		layerInfoTab_->setCurrentIndex(1);
		layerInfoTab_->setTabEnabled(0,false);
		layerInfoTab_->setTabEnabled(2,false);	
		layerInfoTab_->setTabEnabled(3,false);

		foreach(QToolBar* tb,findChildren<QToolBar *>())
		{
			tb->hide();
		}

		foreach(QMenu* m,findChildren<QMenu *>())
		{
			qDebug() << "menu" << m->objectName();

			if(m->objectName() == "controlsMenu" ||
			   m->objectName() == "viewMenu")
				m->setEnabled(false);
		}

		statusBar()->hide();

		/*actionCapability_->setEnabled(false);
		actionStopLoad_->setEnabled(false);
		urlCombo_->setEnabled(false);
		versionCombo_->setEnabled(false);
		formatCombo_->setEnabled(false);
		extraGetMapEdit_->setEnabled(false);
		extraGetCapEdit_->setEnabled(false);

		foreach(QLabel* label,toolBarLabel_)
			label->setEnabled(false);*/	

		getCovInfoMv_->setReadOnly(false);

		getCovInfoMv_->setPlainText(client_->getCovRequest()->request());
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		slotSetGetCovInfo(client_->getCovRequest()->request());

		connect(getCovInfoMv_,SIGNAL(textChanged()),
		     this,SLOT(slotGetCovChanged()));		
	}
	else
	{
		//Run getCapapabilities
		//This will init most of the GUIs 

		layerPanel_->show();
		layerInfoTab_->setTabEnabled(0,true);
		layerInfoTab_->setTabEnabled(2,true);	
		layerInfoTab_->setTabEnabled(3,true);
		layerInfoTab_->setCurrentIndex(0);

		foreach(QToolBar* tb,findChildren<QToolBar *>())
		{
			tb->show();
		}

		foreach(QMenu* m,findChildren<QMenu *>())
		{
			if(m->objectName() == "controlsMenu" ||
			   m->objectName() == "viewMenu")
				m->setEnabled(true);
		}

		statusBar()->show();
		/*actionCapability_->setEnabled(true);
		actionStopLoad_->setEnabled(true);
		urlCombo_->setEnabled(true);
		versionCombo_->setEnabled(true);
		formatCombo_->setEnabled(true);
		extraGetMapEdit_->setEnabled(true);
		extraGetCapEdit_->setEnabled(true);

		foreach(QLabel* label,toolBarLabel_)
			label->setEnabled(true);*/	

		getCovInfoMv_->setReadOnly(true);

		disconnect(getCovInfoMv_,SIGNAL(textChanged()),0,0);

		slotClearLog(true);

		slotRunGetCapabilities();
	}
}

void MvQWcsClientEditor::slotClientModeChanged(QString mode)
{
	if(!clientModeMap_.contains(mode))
		return;
	
	writeSettings(); 

	client_->setClientMode(clientModeMap_[mode]);

	initClientMode();

	readSettings();
}

void MvQWcsClientEditor::loadStarted()
{
	/*loadLabel_->show();
	loadLabel_->movie()->start();*/

	loadProgress_->setRange(0,0);
	loadProgress_->show();
}

void MvQWcsClientEditor::loadFinished()
{
	loadProgress_->hide();
	loadProgress_->setRange(0,1);
	loadProgress_->setValue(1);
	
	/*loadLabel_->movie()->stop();
	loadLabel_->hide();*/		
}

void MvQWcsClientEditor::slotStatusMessage(QString s)
{
	statusMessageLabel_->setText(s);
	//statusBar()->showMessage(s);	
}


void MvQWcsClientEditor::slotSaveInfo()
{	
	client_->slotSaveInfo();
	if(openCb_->isChecked() == false)
	{
		close();
	}
}

//-------------------------------------
//
// Read/write settings
//
//-------------------------------------

void MvQWcsClientEditor::writeSettings()
{	
	if(client_->clientMode() == MvQWcsUiClient::BasicMode)
	{	
		QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Basic");

		settings.beginGroup("mainWindow");
		settings.setValue("geometry",saveGeometry());
		settings.endGroup();
	}
	else
	{
		QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Advanced");

		settings.beginGroup("mainWindow");
		settings.setValue("geometry",saveGeometry());
		settings.setValue("state",saveState());
		settings.setValue("mainSplitter",mainSplitter_->saveState());
		settings.setValue("requestSplitter",requestSplitter_->saveState());
		//settings.setValue("layerSplitter",layerSplitter_->saveState());
		settings.setValue("layerTabIndex",layerTab_->currentIndex());
		settings.setValue("layerInfoTabIndex",layerInfoTab_->currentIndex());
		settings.setValue("actionLogStatus",actionLog_->isChecked());		

		QStringList lst;
		for(int i=0; i < urlCombo_->count(); i++)
		{
			lst << urlCombo_->itemText(i);
		}
		settings.setValue("urlCombo",lst);

		settings.endGroup();
	}

	QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Global");
	settings.beginGroup("mainWindow");
	settings.setValue("openCbStatus",openCb_->isChecked());
	settings.endGroup();

}

void MvQWcsClientEditor::readSettings()
{
	if(client_->clientMode() == MvQWcsUiClient::BasicMode)
	{
		QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Basic");

		settings.beginGroup("mainWindow");
		restoreGeometry(settings.value("geometry").toByteArray());
		restoreState(settings.value("state").toByteArray());
		settings.endGroup();

	}
	else
	{
		QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Advanced");

		settings.beginGroup("mainWindow");
		restoreGeometry(settings.value("geometry").toByteArray());
		restoreState(settings.value("state").toByteArray());
		mainSplitter_->restoreState(settings.value("mainSplitter").toByteArray());
		requestSplitter_->restoreState(settings.value("requestSplitter").toByteArray());
		//layerSplitter_->restoreState(settings.value("layerSplitter").toByteArray());

		if(settings.value("actionLogStatus").isNull())
		{
			actionLog_->setChecked(false);
		}
		else
		{
			actionLog_->setChecked(settings.value("actionLogStatus").toBool());
		}

		//Init tabs
		int ival=settings.value("layerInfoTabIndex").toInt();
		layerInfoTab_->setCurrentIndex(ival);

		ival=settings.value("layerTabIndex").toInt();
		layerTab_->setCurrentIndex(ival);

		QStringList lst(settings.value("urlCombo").toStringList());
		//lst.remove(client_->url())
		urlCombo_->addItems(lst);

		if(client_->url().isEmpty())
			urlCombo_->lineEdit()->clear();


		settings.endGroup();
	}

	QSettings settings("ECMWF","MV4-MvQWcsClientEditor_Global");

	settings.beginGroup("mainWindow");
	if(settings.value("openCbStatus").isNull())
	{
		openCb_->setChecked(true);
	}
	else
	{
		openCb_->setChecked(settings.value("openCbStatus").toBool());
	}
	settings.endGroup();

}
