/***************************** 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 <QLineEdit>
#include <QListWidgetItem>
#include <QListWidget>
#include <QMenu>
#include <QMenuBar>
#include <QPalette>
#include <QProgressBar>
#include <QPushButton>
#include <QScrollArea>
#include <QSettings>
#include <QSignalMapper>
#include <QSplitter>
#include <QStatusBar>
#include <QTextBrowser>
#include <QToolBar>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>

#include "MvQWmsClientEditor.h"

#include "LogHandler.h"

#include "MvQHighlighter.h"
#include "MvQLogBrowser.h"
#include "MvQOgcParam.h"
#include "MvQOgcRequest.h"
#include "MvQOgcTreeModel.h"
#include "MvQTextDialog.h"
#include "MvQTextEditSearchLine.h"
#include "MvQWmsClient.h"


MvQWmsDimensionGuiItem::MvQWmsDimensionGuiItem(MvQOgcDimension* dim,QString text,QGridLayout *parentLayout, int parentRow)
{	
	dim_=dim;

	label_=new QLabel(dim->displayName());

	row_=parentRow;
	parentLayout->addWidget(label_,row_,0);

	//Expand 
	expandTb_= new QToolButton;
	expandTb_->setIcon(QApplication::style()->standardIcon(QStyle::SP_ToolBarHorizontalExtensionButton));
	expandTb_->setCheckable(true);
	expandTb_->setChecked(false);
	//expandTb_->setAutoRaise(true);
	expandTb_->setToolTip(tr("View value list"));
	parentLayout->addWidget(expandTb_,row_,1);

	//LinEdit		
	lineEdit_ = new QLineEdit;
	lineEdit_->setText(text);
	//nameLabel_->setBuddy(lineEdit_);
	
	parentLayout->addWidget(lineEdit_,row_,2);
	
	clearTb_= new QToolButton;
	QIcon icon;
	icon.addPixmap(QPixmap(QString::fromUtf8(":/OgcClient/clear_left.svg")), QIcon::Normal, QIcon::Off);
 	clearTb_->setIcon(icon);	
	clearTb_->setCheckable(false);
	clearTb_->setAutoRaise(true);
	clearTb_->setToolTip(tr("Clear selection"));
	parentLayout->addWidget(clearTb_,row_,3);

	//Get values
	//QStringList values_=dim->displayValues();
	QStringList values_=dim->values();

	list_ = new QListWidget;
	list_->setVisible(false);

	//Populate the list 

	QListWidgetItem* item;
	foreach(QString str,values_)
	{
		item=new QListWidgetItem(str,list_);
		//item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
		//item->setCheckState(Qt::Unchecked);
	}

	parentLayout->addWidget(list_,row_+1,2);

	connect(clearTb_,SIGNAL(clicked(bool)),
		this,SLOT(slotClearText(bool)));
	
	connect(expandTb_,SIGNAL(toggled(bool)),
		this,SLOT(slotSetVisibleList(bool)));

	connect(list_,SIGNAL(itemClicked(QListWidgetItem*)),
		this,SLOT(slotAddItem(QListWidgetItem*)));
	
	/*connect(list_,SIGNAL(itemPressed(QListWidgetItem*)),
		this,SLOT(slotAddItem(QListWidgetItem*)));*/

	connect(list_,SIGNAL(itemChanged(QListWidgetItem*)),
		this, SLOT(slotListItemChanged(QListWidgetItem*)));

	connect(lineEdit_,SIGNAL(textChanged(QString)),
		this, SLOT(slotLineEditChanged(QString)));
}

MvQWmsDimensionGuiItem::~MvQWmsDimensionGuiItem()
{
	delete label_;
	delete lineEdit_;
	delete list_;
	delete expandTb_;
	delete clearTb_;

}

void MvQWmsDimensionGuiItem::slotClearText(bool)
{
	lineEdit_->clear();
}

void MvQWmsDimensionGuiItem::slotSetVisibleList(bool visible)
{
	list_->setVisible(visible);	
}

void MvQWmsDimensionGuiItem::slotLineEditChanged(QString txt)
{
	emit textChanged(dim_,txt);
}

void MvQWmsDimensionGuiItem::slotAddItem(QListWidgetItem* item)
{
	QString text=lineEdit_->text();	
	if(text.size()>0)
	{
		text+=",";
	}
	QString s=item->data(Qt::DisplayRole).toString();
	if(s.contains("Default ("))
	{
		s=dim_->defaultValue();
	}
	text+=s;

	lineEdit_->setText(text);
}

void MvQWmsDimensionGuiItem::slotListItemChanged(QListWidgetItem* item)
{
	QString text=lineEdit_->text();
	if(item->checkState() == Qt::Checked)
	{
		if(text.size()>0)
		{
			text+="/";
		}
		text+=item->data(Qt::DisplayRole).toString();
	}
	else
	{
		QString itemText=item->data(Qt::DisplayRole).toString();
		QStringList textList=text.split("/");
		int itemIndex=textList.indexOf(itemText);
		
		QString newText;
		for(int i=0;i < textList.count(); i++)
		{
			if(i != 0 && i != itemIndex)
			{
				newText+="/";
			}
			if(i != itemIndex)
			{	
				newText+=textList[i];
			}
		}
		text=newText;
	}

	lineEdit_->setText(text);

}	

void  MvQWmsDimensionGuiItem::addValue(QString value)
{
	QListWidgetItem* item;
	item=new QListWidgetItem(value,list_);
	//item->setFlags(Qt::ItemIsSelectable |Qt::ItemIsEnabled);
	//item->setCheckState(Qt::Unchecked);
}

QString MvQWmsDimensionGuiItem::currentValue()
{
	QString text=lineEdit_->text();
	return text;
} 

//================================
//
// MvQWmsClientEditor
//
//================================

MvQWmsClientEditor::MvQWmsClientEditor(MvQWmsUiClient *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(iconName + " - WMS Client Editor- Metview");
	setWindowIcon(QPixmap(":/OgcClient/WMS_CLIENT.svg"));
	
	client_ = client;

	//ClientModeMap	
	clientModeMap_["Plain"]=MvQWmsUiClient::BasicMode;
	clientModeMap_["Interactive"]=MvQWmsUiClient::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() ==MvQWmsUiClient::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
	//-------------

	//actions
	setupFileActions();
	setupViewActions();
	setupSettingsActions();
	
	// Setup menus and toolbars
	setupMenus(menuItems_);

	QToolBar* tb=findToolBar(MvQMainWindow::SettingsMenu);
	if(tb) 
	{
	  	advancedModeOnlyWidgets_ << tb;  
		insertToolBarBreak(tb);
	}	
		
	//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(getCapabilityLoaded()),
		this,SLOT(slotGetCapabilityLoaded()));

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

	connect(client_,SIGNAL(clientResetDone()),
		this,SLOT(slotClientReset()));

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

	//
	readSettings();
}	

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

void MvQWmsClientEditor::setupFileActions()
{
	QAction *actionImport = new QAction(this);
        actionImport->setObjectName(QString::fromUtf8("actionImport"));
	actionImport->setText(tr("&Import"));
	actionImport->setToolTip(tr("Import request"));

	//Define routines
	connect(actionImport,SIGNAL(activated()),
		this,SLOT(slotImportRequest()));

	MvQMainWindow::MenuType menuType=MvQMainWindow::FileMenu;
	menuItems_[menuType].push_back(new MvQMenuItem(actionImport,MvQMenuItem::MenuTarget));
}


void MvQWmsClientEditor::setupViewActions()
{
  	//---------------------
	// First toolbar row
	//---------------------
//
	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 icon2;
	icon2.addPixmap(QPixmap(QString::fromUtf8(":/examiner/log.svg")), QIcon::Normal, QIcon::Off);
 	actionLog_->setIcon(icon2);	

	logPanel_->hide();

	//Define routines
	connect(actionLog_,SIGNAL(toggled(bool)),
		logPanel_,SLOT(setVisible(bool)));
		
	QAction* actionSeparator = new QAction(this);	
	actionSeparator->setSeparator(true);	
		
	actionCapability_ = new QAction(this);
        actionCapability_->setObjectName(QString::fromUtf8("actionCapability"));
	actionCapability_->setText(tr("&Load GetCapabilities"));
	actionCapability_->setToolTip(tr("Load GetCapabilities"));
	actionCapability_->setShortcut(tr("F5"));
	QIcon icon;
	icon.addPixmap(QPixmap(QString::fromUtf8(":/OgcClient/reload.svg")), 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"));
	actionStopLoad_->setShortcut(tr("Esc"));
	QIcon icon1;
	icon1.addPixmap(QPixmap(QString::fromUtf8(":/OgcClient/remove.svg")), 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);
	urlCombo_->setMaximumWidth(700);
	advancedModeOnlyWidgets_ << urlCombo_;

	//Server version combo
	QLabel *labelVersion= new QLabel(tr(" Version:"));
	advancedModeOnlyWidgets_ << labelVersion;
	versionCombo_ = new QComboBox;
	advancedModeOnlyWidgets_ << versionCombo_;
	
	QStringList lst;
	lst << "Default" << "1.0.0" << "1.1.0" << "1.1.1" << "1.3.0";
	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(versionCombo_,SIGNAL(activated(QString)),
		this,SLOT(slotSelectVersion(QString)));

	MvQMainWindow::MenuType menuType=MvQMainWindow::ViewMenu;
	menuItems_[menuType].push_back(new MvQMenuItem(actionLog_));
	menuItems_[menuType].push_back(new MvQMenuItem(actionSeparator));
	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));

}	
void MvQWmsClientEditor::setupSettingsActions()
{	
	//---------------------
	// Second toolbar row
	//--------------------

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

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

	//Extra getmap
	QLabel *labelGetMap= new QLabel(tr(" Extra getMap param:"));
	extraGetMapEdit_= new QLineEdit("");	
	
	QString mName="Format";

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

	MvQMainWindow::MenuType menuType=MvQMainWindow::SettingsMenu;
	
	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(labelGetMap,MvQMenuItem::ToolBarTarget));
	menuItems_[menuType].push_back(new MvQMenuItem(extraGetMapEdit_,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(extraGetMapEdit_,SIGNAL(textChanged(QString)),
		this,SLOT(slotExtraGetMapChanged(QString)));
}


void MvQWmsClientEditor::setupLayerPanel(QVBoxLayout *layout)
{
	QLabel *label;
	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("WmsLayerTree");
	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"));

	//-------------------
	// 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++;

	
	crsLabel_= new QLabel("CRS:");
	crsCombo_ = new QComboBox;
	layerGrid_->addWidget(crsLabel_, 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
	previewPb_ = new QPushButton(tr("Generate preview"));
	layout->addWidget(previewPb_);

	connect(previewPb_,SIGNAL(clicked()),
		this,SLOT(slotPreview()));
}

void MvQWmsClientEditor::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();

	//--------------------------	
	// Layer preview tab
	//--------------------------

	layerPreview_ = new QTextBrowser;
	layerPreview_->setReadOnly(true);
	layerPreview_->document()->setDefaultStyleSheet(cssDoc);
	layerPreview_->setWordWrapMode(QTextOption::WordWrap);

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

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

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

	connect(client_,SIGNAL(logoLoaded(QString)),
		this,SLOT(slotLogoLoaded(QString)));

	//--------------------------	
	// GetMap request tab
	//--------------------------

	//---------------------------------------
	// --> Request editor (plain mode only)
	//---------------------------------------
	
	reqSplitter_=new QSplitter;
	layerInfoTab_->addTab(reqSplitter_,tr("GetMap request"));

	reqEditPanel_=new QWidget;
	QVBoxLayout *reqEditLayout=new QVBoxLayout;
	reqEditPanel_->setLayout(reqEditLayout);
	reqSplitter_->addWidget(reqEditPanel_);

	label=new QLabel(tr("Editable request parameters:"));
	reqEditLayout->addWidget(label);

	reqEditSa_=new QScrollArea;
	reqEditSa_->setWidgetResizable(true);
	reqEditSa_->setFrameShape(QFrame::NoFrame);
	reqEditLayout->addWidget(reqEditSa_);

	reqEditPanel_->hide();
		
	//---------------------------------------
	// --> Request display
	//---------------------------------------
	
	w=new QWidget;
	QVBoxLayout *mapInfoLayout=new QVBoxLayout;
	w->setLayout(mapInfoLayout);
	reqSplitter_->addWidget(w);

	QString s="Individual requests (maximum ";
	s+=QString::number(MvQGetMapRequest::maxFrame()) + "):";
	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);
	//reqSplitter_->addWidget(reqGrid_);
	mapInfoLayout->addWidget(getMapInfoSplit_,1);

	highlighterSplit_ = new MvQHighlighter(getMapInfoSplit_->document());
	
	//---------------------------------------
	// --> Load preview (plain mode only)
	//---------------------------------------

	plainPreviewPanel_=new QWidget;
	plainPreviewPanel_->setMinimumHeight(128);
	
	QVBoxLayout *plainPreLayout = new QVBoxLayout;
	plainPreLayout->setContentsMargins(0,0,0,0);
	plainPreviewPanel_->setLayout(plainPreLayout);
	mapInfoLayout->addWidget(plainPreviewPanel_);

	label=new QLabel(tr("Preview:"));
	plainPreLayout->addWidget(label);

	plainPreviewLabel_=new QLabel;
	plainPreviewLabel_->setFrameStyle(QFrame::Box | QFrame::Plain);
	//plainPreviewLabel_->setFixedSize(QSize(256,128));
	plainPreviewLabel_->setFixedWidth(260);
	plainPreviewLabel_->setMinimumHeight(128);
	plainPreviewLabel_->setAutoFillBackground(true);
	
	QPalette pal=plainPreviewLabel_->palette();
	//QColor col=pal.color(QPalette::Window).lighter(120);
	pal.setColor(QPalette::Window,Qt::white);
	plainPreviewLabel_->setPalette(pal);
		
	plainPreLayout->addWidget(plainPreviewLabel_);

	plainPreviewPb_=new QPushButton(tr("Generate preview"));
	//plainPreLayout->addWidget(plainPreviewPb_);
	reqEditLayout->addWidget(plainPreviewPb_);

	plainPreviewPanel_->hide();
	
	connect(plainPreviewPb_,SIGNAL(clicked()),
		this,SLOT(slotPreview()));

	connect(client_,SIGNAL(getMapRequestChanged(QString,QStringList)),
		this,SLOT(slotSetGetMapInfo(QString,QStringList)));

	//------------------------	
	// GetCapabilities tab
	//------------------------

	w=new QWidget;
	layerInfoTab_->addTab(w,tr("GetCapabilities"));

	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_);

	highlighterGetCap_ = new MvQWmsGetCapHighlighter(getCapInfo_->document());
	
	//--------------------------	
	// Service meta-data  tab
	//--------------------------
	
	highlighterGetCap_ = new MvQWmsGetCapHighlighter(getCapInfo_->document());

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

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

}
void MvQWmsClientEditor::setupReqEditPanel()
{
	if(reqEditSa_->widget())
		return;

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

	reqEditSa_->setWidget(w);

	QLabel* label;
	QLineEdit *le;
	QTextEdit *te;
	QSignalMapper *sigMapper = new QSignalMapper(this);
	QStringList labelText, key;

	labelText << tr("URL:") << tr("Version:") <<  tr("Layer:") << tr("Style:") 
		  << tr("CRS/SRS:") <<  tr("BBox:") <<  tr("Width:") << tr("Height:")
		  << tr("Format:") <<  tr("Transparent:") <<  tr("Extra params:") << tr("Time:") 
		  << tr("Elevation:");

	key << "mv_key_url" << "VERSION" <<  "LAYERS" << "STYLES" 
		  << "mv_key_crs" <<  "BBOX" <<  "WIDTH" << "HEIGHT"
		  << "FORMAT" <<  "TRANSPARENT" <<  "mv_key_extrapar" << "TIME"
		  << "ELEVATION";

	int row=0;
	for(int i=0; i < labelText.count(); i++)
	{
		label=new QLabel(labelText[i]);
		reqLe_[key[i]] = new QLineEdit;
		le=reqLe_[key[i]];

		reqGrid->addWidget(label,row,0);	
		reqGrid->addWidget(le,row,1);
		row++;

		connect(le,SIGNAL(textEdited(QString)),
			sigMapper,SLOT(map()));
		sigMapper->setMapping(le,key[i]);
	}

	labelText.clear();
	key.clear();

	labelText <<  tr("Temporal<br>dimensions:") <<  tr("Other<br>dimensions");
	key <<  tr("mv_key_tdim") <<  tr("mv_key_otherdim");

	for(int i=0; i < labelText.count(); i++)
	{
		label=new QLabel(labelText[i]);
		reqTe_[key[i]] = new QTextEdit;
		te=reqTe_[key[i]];

		reqGrid->addWidget(label,row,0);	
		reqGrid->addWidget(te,row,1);
		row+=3;

		connect(te,SIGNAL(textChanged()),
			sigMapper,SLOT(map()));
		sigMapper->setMapping(te,key[i]);
	}


	connect(sigMapper, SIGNAL(mapped(const QString &)),
                this, SLOT(slotReqEdited(const QString &)));

	
	qDebug() << sigMapper;

}


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

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

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

void MvQWmsClientEditor::clearServerDependentData()
{
	formatCombo_->clear();
	
	clearLayerDependentData();
	getMapInfoSplit_->clear();	
	getCapInfo_->clear();	
}

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

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

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

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

	//Remove previous dimension widgets from the grid
	for(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 MvQWmsClientEditor::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,QColor(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 MvQWmsClientEditor::initExtraParEdit()
{
	QString value=client_->extraGetCapPar();
	extraGetCapEdit_->setText(value);

	value=client_->extraGetMapPar();
	extraGetMapEdit_->setText(value);
}	

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

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

	//Try to expand the first child of the root node
	if(layerModel_->rowCount(QModelIndex()) > 0)
	{
		QModelIndex index=layerModel_->index(0,0,QModelIndex());
		layerTree_->expand(index);
	}
	
/*	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 MvQWmsClientEditor::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 MvQWmsClientEditor::initCrsCombo()
{
	crsLabel_->setText(client_->crsDisplayName());

	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,QColor(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 MvQWmsClientEditor::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
//
//------------------------------------------
/*!
  Replaces the URL combobox's curret text with the given url and runs getCapabilities.   
*/
void MvQWmsClientEditor::slotSelectUrl(const QString &url)
{
	client_->setUrl(url,versionCombo_->currentText());
	slotRunGetCapabilities();
}

/*!
  Removes duplicates from the URL combobox and trims down
  the its size to a predefined number. This method should be called
  whenever a new item is inserted into the combo box.   
*/

void MvQWmsClientEditor::checkUrlComboItems()
{
	qDebug() << "checkUrlComboItems";
  
  	//Duplicates are removed first!
	QMap<QString,int> cntMap;
	for(int i=0; i < urlCombo_->count(); i++)
	{
		QString s=urlCombo_->itemText(i);
		//qDebug() << s;		
		if(cntMap.find(s) == cntMap.end())
		{
		  	cntMap[s]=1;
		}
		else
		{
		  	cntMap[s]=cntMap[s]+1;
		}	
	}	
	
	//qDebug() << cntMap;

	foreach(QString s,cntMap.keys())
	{
		int itemCnt=cntMap[s];
		if(itemCnt > 1)
		{
		  	for(int i=urlCombo_->count()-1; i >= 0 && itemCnt > 1; i--)
			{
				if(urlCombo_->itemText(i) == s)
				{  
				  	//qDebug() << "remove" << i << urlCombo_->currentIndex() <<  urlCombo_->itemText(i) <<  urlCombo_->currentText();
					urlCombo_->removeItem(i);
					//qDebug() << urlCombo_->currentText();
					itemCnt--;
				}
			}
		}
	}	
	
	
	//for(int i=0; i < urlCombo_->count(); i++)
	//	qDebug() << "after" << urlCombo_->itemText(i);
	
	//Trim down the combo size to maxCount
	int maxCount=25;
	for(int i=urlCombo_->count()-1; i > maxCount; i--)
	{
		urlCombo_->removeItem(i);
	}
}

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

void MvQWmsClientEditor::slotRunGetCapabilities()
{	
	//Check if the  URL combobox's current text was
	//inserted into URL combobox.  	
	client_->setUrl(urlCombo_->currentText(),versionCombo_->currentText());	
	
	clearServerDependentData();

	if(client_->url().isEmpty())
	{
		urlCombo_->clearEditText();
		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_->slotRunGetCapabilities();
}

void MvQWmsClientEditor::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();
	setupLayerList();

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

	loadFinished();
		
	//slotPreviewLoaded(QString());


	getCapInfo_->setPlainText(client_->getCapabilityDoc());
	slotUpdateServiceInfo(); 
	//serviceInfo_->setPlainText(client_->serviceTitle());

	//loadFinished();

	slotUpdateLayerInfo();
	loadStarted();
	client_->downloadLogo();
	
	if(urlCombo_->findText(urlCombo_->currentText()) == -1)
	{	  		
		//for(int i=0; i < urlCombo_->count(); i++)
		//	qDebug() << urlCombo_->itemText(i)	
	
		// urlCombo_->currentText();
		disconnect(urlCombo_, SIGNAL(activated(QString)),0,0);
		urlCombo_->insertItem(0,urlCombo_->currentText());
		urlCombo_->setCurrentIndex(0);	
		connect(urlCombo_, SIGNAL(activated(QString)),
			   this,SLOT(slotSelectUrl(QString)));			   
		// urlCombo_->currentText();		

		checkUrlComboItems();					
		//qDebug() << urlCombo_->currentText();
	}
	else
	{
		checkUrlComboItems();		  
	}  
	
}

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

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

	//slotPreviewLoaded(QString());

	slotUpdateLayerInfo();
	loadStarted();
	client_->downloadLogo();
}

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

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

void MvQWmsClientEditor::slotExtraGetMapChanged(QString val)
{
	client_->setExtraGetMapPar(val);
}

void MvQWmsClientEditor::slotPreview()
{
	if(client_->clientMode() == MvQWmsUiClient::AdvancedMode)
	{
	 	previewPb_->setEnabled(false);
		actionCapability_->setEnabled(false);
		actionStopLoad_->setEnabled(true);
		requestSplitter_->widget(0)->setEnabled(false);
		clientModeCombo_->setEnabled(false);

		loadStarted();
		client_->downloadPreview();
	}
	else
	{
	  	plainPreviewPb_->setEnabled(false);
	  	actionStopLoad_->setEnabled(true);
		clientModeCombo_->setEnabled(false);
		
		loadStarted();
		client_->downloadPreview(QSize(256,128));	  
	}  
}


void MvQWmsClientEditor::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 << "ContactPerson" << "ContactOrganization" << "ContactPosition" << 
				"AddressType" << "Address" << "City" << "StateOrProvince" <<
				"PostCode" << "Country" << "ContactVoiceTelephone" <<
				"ContactFacsimileTelephone" << "ContactElectronicMailAddress";

	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 MvQWmsClientEditor::slotUpdateLayerInfo()
{
	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\">" + client_->crsDisplayName().remove(":") + "</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>";
	s+="<td class=\"image\" align=center>Preview not loaded</td></tr>";

	s+="</tr>";
	s+="<tr><td class=\"first\">Legend</td>";
	s+="<td class=\"image\" align=center>Legend not loaded</td></tr>";

	s+="<tr><td class=\"first\">Logo</td>";
	s+="<td class=\"image\" align=center>Logo not loaded</td></tr>";

	s+="</tbody></table>";

	layerPreview_->setHtml(s);
}

void MvQWmsClientEditor::slotPreviewLoaded(QString path)
{
	if(client_->clientMode() == MvQWmsUiClient::AdvancedMode)
	{
	 	QString txt=layerPreview_->toHtml();
	
		if(!path.isEmpty())	
		{
			QString s="<img src=\"" + path + "\">";
			txt.replace("Preview not loaded",s);
			layerPreview_->setHtml(txt);
		}

		loadFinished();
		loadStarted();
		client_->downloadLegend();
	}
	else
	{
	  	loadFinished();
		plainPreviewLabel_->setPixmap(QPixmap(path));
		
		plainPreviewPb_->setEnabled(true);
		actionStopLoad_->setEnabled(false);
		clientModeCombo_->setEnabled(true);
	}	
	
}

void MvQWmsClientEditor::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 MvQWmsClientEditor::slotLogoLoaded(QString logoPath)
{
	QString txt=layerPreview_->toHtml();
	
	if(!logoPath.isEmpty())	
	{
		QString s="<img src=\"" + logoPath + "\">";
		txt.replace("Logo not loaded",s);
		layerPreview_->setHtml(txt);
	}

	loadFinished();
}

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

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

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

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



void MvQWmsClientEditor::slotSetGetMapInfo(QString req,QStringList reqSplit)
{
	QString  s;
	if(!req.isEmpty())
	{
		QString getMaps;
		s="<table><tbody>";	
		s+="<tr><th class=\"first\">Frame</th><th>Request</th></tr>";

		int i=1;
		foreach(QString r,reqSplit)
		{
			s+="<tr><td class=\"first\">" + QString::number(i) + "</td><td>" + r + "</td></tr>";
			i++;
		}
		s+="</tbody></table>";
	}

	getMapInfoSplit_->setHtml(s);
	
}

void MvQWmsClientEditor::slotReqEdited(const QString &id)
{
	MvQGetMapRequest *req=client_->getMapRequest();
	if(reqLe_.find(id) != reqLe_.end())
	{
		QString s=reqLe_[id]->text();
		req->setItem(id,s);
		client_->setGetMapRequest(req->request());
	}	
	else if(reqTe_.find(id) != reqTe_.end())
	{
		QString s=reqTe_[id]->toPlainText();
		req->setItem(id,s);
		client_->setGetMapRequest(req->request());
	}
}

void MvQWmsClientEditor::slotClientReset()
{
	if(client_->clientMode() == MvQWmsUiClient::BasicMode)
	{
		slotSetGetMapInfo(client_->getMapRequest()->request(),client_->getMapRequest()->requestFrame());

		MvQGetMapRequest* req=client_->getMapRequest();
		QMapIterator<QString,QLineEdit*> itLe(reqLe_);
		while(itLe.hasNext())
		{
			itLe.next();
			itLe.value()->setText(req->item(itLe.key()));
		}
		QMapIterator<QString,QTextEdit*> itTe(reqTe_);
		while(itTe.hasNext())
		{
			itTe.next();
			itTe.value()->setPlainText(req->item(itTe.key()));
		}
	}	
	else
	{
		initExtraParEdit();

		//Init  url
		if(client_->url().isEmpty() || urlCombo_->itemText(0) != client_->url())
		{	
			urlCombo_->insertItem(0,client_->url());
			urlCombo_->setCurrentIndex(0);
		}
	
		slotRunGetCapabilities();		
	}
}

void MvQWmsClientEditor::initClientMode()
{	
	if(client_->clientMode() == MvQWmsUiClient::BasicMode)
	{
	  	//Toolbar  + menubar  + log 
		actionCapability_->setEnabled(false);
		actionStopLoad_->setEnabled(false);
		
		foreach(QWidget *w,advancedModeOnlyWidgets_)
		{
		  	w->setEnabled(false);
		}
		
		slotClearLog(true);
		slotStatusMessage("");

		//Layer tabs
	 	layerPanel_->hide();
		clearLayerDependentData();

		layerInfoTab_->setCurrentIndex(1);
		layerInfoTab_->setTabEnabled(0,false);
		layerInfoTab_->setTabEnabled(2,false);	
		layerInfoTab_->setTabEnabled(3,false);
		
		plainPreviewLabel_->clear();
		
		plainPreviewPanel_->show();

		
		//This build the scrollarea and the request editors
		setupReqEditPanel();

		MvQGetMapRequest* req=client_->getMapRequest();
		QMapIterator<QString,QLineEdit*> itLe(reqLe_);
		while(itLe.hasNext())
		{
			itLe.next();
			itLe.value()->setText(req->item(itLe.key()));
		}
		QMapIterator<QString,QTextEdit*> itTe(reqTe_);
		while(itTe.hasNext())
		{
			itTe.next();
			itTe.value()->setPlainText(req->item(itTe.key()));
		}
		
		reqEditPanel_->show();

	}
	else
	{		
		actionCapability_->setEnabled(true);
		actionStopLoad_->setEnabled(false);
		
		foreach(QWidget *w,advancedModeOnlyWidgets_)
		{
		  	w->setEnabled(true);
		}
	
		slotClearLog(true);
		slotStatusMessage("");

		layerPanel_->show();
		layerInfoTab_->setTabEnabled(0,true);
		layerInfoTab_->setTabEnabled(2,true);	
		layerInfoTab_->setTabEnabled(3,true);
		layerInfoTab_->setCurrentIndex(0);
		
		plainPreviewPanel_->hide();
		reqEditPanel_->hide();
		
		slotClearLog(true);

		initExtraParEdit();

		//Init  url
		if(client_->url().isEmpty() || urlCombo_->itemText(0) != client_->url())
		{	
			urlCombo_->insertItem(0,client_->url());
		}		
		urlCombo_->setCurrentIndex(0);
	
		//Run getCapapabilities
		//This will init most of the GUIs 
		slotRunGetCapabilities();
	}
}

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

	client_->setClientMode(clientModeMap_[mode]);

	initClientMode();

	readSettings();
}

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

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

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

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


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

void MvQWmsClientEditor::slotImportRequest()
{	
	MvQTextDialog diag(tr("Import GetMap request"),tr("GetMap request:"),tr("Import"));
	
	if(diag.exec() == QDialog::Accepted)
	{
		if(!diag.text().isEmpty())
			client_->reset(diag.text());
	}
}

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

void MvQWmsClientEditor::writeSettings()
{	
	if(client_->clientMode() == MvQWmsUiClient::BasicMode)
	{	
		QSettings settings("ECMWF","MV4-MvQWmsClientEditor_Basic");

		settings.beginGroup("mainWindow");
		settings.setValue("geometry",saveGeometry());
		settings.endGroup();
	}
	else
	{
		QSettings settings("ECMWF","MV4-MvQWmsClientEditor_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());	

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

		settings.endGroup();
	}

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

}

void MvQWmsClientEditor::readSettings()
{
	if(client_->clientMode() == MvQWmsUiClient::BasicMode)
	{
		QSettings settings("ECMWF","MV4-MvQWmsClientEditor_Basic");

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

	}
	else
	{
		QSettings settings("ECMWF","MV4-MvQWmsClientEditor_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());
		
		//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-MvQWmsClientEditor_Global");

	settings.beginGroup("mainWindow");

	if(settings.value("actionLogStatus").isNull())
	{
		actionLog_->setChecked(false);
	}
	else
	{
		actionLog_->setChecked(settings.value("actionLogStatus").toBool());
	}
	
	if(settings.value("openCbStatus").isNull())
	{
		//We set it to false by default
	  	openCb_->setChecked(false);
	}
	else
	{
		openCb_->setChecked(settings.value("openCbStatus").toBool());
	}
	settings.endGroup();

}
