/***************************** 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 <QDebug>
#include <QLabel>
#include <QHBoxLayout>
#include <QMenu>
#include <QSlider>
#include <QSpinBox>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>

#include "MvQLayerWidget.h"
#include "MvQLayerContentsIcon.h"
#include "MvQLayerModel.h"

MvQLayerWidget::MvQLayerWidget(MgQPlotScene *scene,QWidget *parent) : QWidget(parent)
{	
	QVBoxLayout *layerVb=new QVBoxLayout;
	layerVb->setContentsMargins(2,2,2,2);
	setLayout(layerVb);
			
	//Create layer model and view	
	view_ = new QTreeView(this);
	view_->setItemDelegate(new MvQLayerDelegate());
	layerVb->addWidget(view_);	

	model_= new MvQLayerModel(scene);
	view_->setModel(model_);

	//view_->setRootIsDecorated(false);

	view_->setDragEnabled(true);
 	view_->setAcceptDrops(true);
 	view_->setDropIndicatorShown(true);
	view_->setDragDropMode(QAbstractItemView::DragDrop);
	
	/*view_->setContextMenuPolicy(Qt::CustomContextMenu);

	connect(view_,SIGNAL(customContextMenuRequested(const QPoint &)),
                this,SLOT(slotContextMenu(const QPoint &)));*/
		
		
	QPalette pal = view_->palette();
	pal.setColor(QPalette::Highlight,Qt::white);
	//view_->setPalette(pal);
	
	//Slider
	QHBoxLayout *hb = new QHBoxLayout;
	layerVb->addLayout(hb);
	
	QLabel *label=new QLabel(tr("Transparency (%)"));
	hb->addWidget(label);	

	trSlider_ = new QSlider;
	trSlider_->setOrientation(Qt::Horizontal);
	trSlider_->setMinimum(0);
	trSlider_->setMaximum(100);
	trSlider_->setToolTip(tr("Change layer transparency"));
	hb->addWidget(trSlider_);		
	
	trSpin_ = new QSpinBox;
	trSpin_->setMinimum(0);
	trSpin_->setMaximum(100);
	trSpin_->setToolTip(tr("Change layer transparency"));
	hb->addWidget(trSpin_);	

	initTrWidgets_=false;

	connect(trSlider_,SIGNAL(valueChanged(int)),
		this,SLOT(slotTrSliderValueChanged(int)));

	connect(trSlider_,SIGNAL(sliderReleased()),
		this,SLOT(slotTrSliderReleased()));

	connect(trSpin_,SIGNAL(valueChanged(int)),
		this,SLOT(slotTrSpinValueChanged(int)));
		
	//Buttons
	hb = new QHBoxLayout;
	layerVb->addLayout(hb);

	topTb_ = new QToolButton(this);
	topTb_->setToolTip(tr("Move the current layer to the top"));
	topTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/arrow_top.svg")));

	upTb_ = new QToolButton(this);
	upTb_->setToolTip(tr("Move the current layer up"));
  	upTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/arrow_up.svg")));

	downTb_ = new QToolButton(this);
	downTb_->setToolTip(tr("Move the current layer down"));
	downTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/arrow_down.svg")));

	bottomTb_ = new QToolButton(this);
	bottomTb_->setToolTip(tr("Move the current layer to the bottom"));
	bottomTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/arrow_bottom.svg")));
	
	hb->addWidget(topTb_);
	hb->addWidget(upTb_);
	hb->addWidget(downTb_);
	hb->addWidget(bottomTb_);
	hb->addStretch(1.);
	
	connect(topTb_,SIGNAL(clicked()),
		this,SLOT(slotMoveTop()));

	connect(upTb_,SIGNAL(clicked()),
		this,SLOT(slotMoveUp()));

	connect(downTb_,SIGNAL(clicked()),
		this,SLOT(slotMoveDown()));

	connect(bottomTb_,SIGNAL(clicked()),
		this,SLOT(slotMoveBottom()));
		
	connect(view_,SIGNAL(clicked(const QModelIndex &)),
		this,SLOT(slotSelectLayer(const QModelIndex &)));

	connect(model_,SIGNAL(layerDragFinished()),
		this,SLOT(slotCheckItemStatus()));
		
	connect(model_,SIGNAL(layerTransparencyChanged(QString,int)),
		this,SIGNAL(layerTransparencyChanged(QString,int)));	
		
	connect(model_,SIGNAL(layerVisibilityChanged(QString,bool)),
		this,SIGNAL(layerVisibilityChanged(QString,bool)));
		
	//connect(model_,SIGNAL(layerStackingOrderChanged(QList<QPair<QString,int> >)),
	//	this,SIGNAL(layerStackingOrderChanged(QList<QPair<QString,int> >)));	
		
}		


MvQLayerWidget::~MvQLayerWidget()
{
  
}

MgQLayerItem* MvQLayerWidget::currentLayer()
{
	int row=view_->currentIndex().row(); 
	return model_->rowToLayer(row);
}  

QString MvQLayerWidget::currentLayerText()
{
	return model_->data(view_->currentIndex()).toString();  
}  

void MvQLayerWidget::slotSelectLayer(MgQLayerItem* layer)
{
	int row=model_->layerToRow(layer);
	QModelIndex index=model_->index(row,0);
	slotSelectLayer(index);
}

void MvQLayerWidget::slotSelectLayer(const QModelIndex &index)
{
	if(index != view_->currentIndex())
	{
		view_->setCurrentIndex(index);
	}
	
	int value=model_->transparency(index);

	slotCheckItemStatus();

	initTrWidgets_=true;
	trSlider_->setValue(value);
	trSpin_->setValue(value);
	initTrWidgets_=false;
}


void MvQLayerWidget::slotTrSpinValueChanged(int value)
{
	if(initTrWidgets_)
		return;

	trSlider_->setValue(value);
	changeTransparency(value);
}

void MvQLayerWidget::slotTrSliderValueChanged(int value)
{
	if(initTrWidgets_)
		return;
	
	initTrWidgets_=true;
	trSpin_->setValue(value);
	initTrWidgets_=false;
	
}

void MvQLayerWidget::slotTrSliderReleased()
{
	int value=trSlider_->value();	
	changeTransparency(value);
}

void MvQLayerWidget::changeTransparency(int value)
{
	model_->setTransparency(view_->currentIndex(),value);
}

void MvQLayerWidget::slotMoveTop()
{
	model_->moveTop(view_->currentIndex());
	view_->setCurrentIndex(model_->index(0,0));
	slotCheckItemStatus();
}

void MvQLayerWidget::slotMoveUp()
{
	int row=view_->currentIndex().row();
	//QModelIndex parent=view_->currentIndex().parent();

	model_->moveUp(view_->currentIndex());
	view_->setCurrentIndex(model_->index(row-1,0));
	slotCheckItemStatus();
}

void MvQLayerWidget::slotMoveBottom()
{
	model_->moveBottom(view_->currentIndex());

	int num=model_->rowCount(QModelIndex());
	view_->setCurrentIndex(model_->index(num-1,0));
	slotCheckItemStatus();
}

void MvQLayerWidget::slotMoveDown()
{
	int row=view_->currentIndex().row();
	//QModelIndex parent=view_->currentIndex().parent();

	model_->moveDown(view_->currentIndex());	
	view_->setCurrentIndex(model_->index(row+1,0));
	slotCheckItemStatus();
}

void MvQLayerWidget::slotCheckItemStatus()
{
	if(!view_->currentIndex().isValid())
	{
		trSlider_->setEnabled(false);
		trSpin_->setEnabled(false);
		topTb_->setEnabled(false);
		upTb_->setEnabled(false);
		bottomTb_->setEnabled(false);
		downTb_->setEnabled(false);
	}
	else
	{
		trSlider_->setEnabled(true);
		trSpin_->setEnabled(true);
		
		int row=view_->currentIndex().row();
		int num=model_->rowCount(QModelIndex());
	
		if(num==1)
		{
			topTb_->setEnabled(false);
			upTb_->setEnabled(false);
			downTb_->setEnabled(false);
			bottomTb_->setEnabled(false);
		}
		else if(row==0)
		{
			topTb_->setEnabled(false);
			upTb_->setEnabled(false);
			downTb_->setEnabled(true);
			bottomTb_->setEnabled(true);
		}		
		else if(row==num-1)
		{
			topTb_->setEnabled(true);
			upTb_->setEnabled(true);
			downTb_->setEnabled(false);
			bottomTb_->setEnabled(false);
		}
		else 
		{
			topTb_->setEnabled(true);
			upTb_->setEnabled(true);
			downTb_->setEnabled(true);
			bottomTb_->setEnabled(true);
		}
	}
}

void MvQLayerWidget::slotContextMenu(const QPoint &position)
{
	QModelIndex index=view_->indexAt(position); 
		
	if(!index.isValid() || model_->indexToLevel(index) == 0)
	  	return;
	
	qDebug() << "Selected: " << model_->data(index,Qt::DisplayRole).toString();	  
	
	MvQLayerContentsIcon *icon=model_->indexToIcon(index);
	if(!icon)
	  	return;
		
	QList<QAction*> actions;

	//Inser new key
	QAction *actionEdit = new QAction(this);
        actionEdit->setObjectName(QString::fromUtf8("actionEdit"));
	actionEdit->setText(tr("Edit"));
	actions.append(actionEdit);
	if(!icon->canBeEdited())
	 	actionEdit->setEnabled(false); 
	
	//Inser new key
	QAction *actionSave = new QAction(this);
        actionSave->setObjectName(QString::fromUtf8("actionSave"));
	actionSave->setText(tr("Save"));
	actions.append(actionSave);
	if(!icon->canBeSaved())
	 	actionSave->setEnabled(false); 

	QAction *actionDelete = new QAction(this);
        actionDelete->setObjectName(QString::fromUtf8("actionDelete"));
	actionDelete->setText(tr("Delete"));
	actions.append(actionDelete);
	if(!icon->canBeDeleted())
	 	actionDelete->setEnabled(false); 
		
	QAction *res=QMenu::exec(actions,view_->mapToGlobal(position));	
	if(res == actionEdit) 
	{
		qDebug() << "Context menu: Edit"; 
		icon->startEditor();
	}  
	else if(res == actionSave) 
	{
		qDebug() << "Context menu: Save"; 				
	} 
	else if(res == actionDelete) 
	{
		qDebug() << "Context menu: Delete"; 				
	}  
		
	foreach(QAction *ac,actions)
	  	delete ac;
}

void MvQLayerWidget::slotFrameChanged()
{
}

void MvQLayerWidget::layersAreAboutToChange()
{
	//Save expand state
	QModelIndexList indexLst=model_->match(model_->index(0,0),
			    Qt::DisplayRole,"*",-1,
		            Qt::MatchWildcard | Qt::MatchRecursive);
	
	expandList_.clear();	
	foreach(QModelIndex index,indexLst)
	{
		if(view_->isExpanded(index))
			expandList_ << index;
	}	
  
	model_->layersAreAboutToChange();	
}

/*void MvQLayerWidget::reset(MgQSceneItem *sceneItem,int layerIndex)
{
  	model_->resetLayers(sceneItem);
	
	QModelIndex index=model_->index(layerIndex,0);
	if(!index.isValid())
	{
		index=model_->index(model_->rowCount()-1,0);
	}

	if(index.isValid())
	{
		slotSelectLayer(index);
	}
	else
	{
		slotCheckItemStatus();
	}	
}*/

void MvQLayerWidget::reset(MgQSceneItem *sceneItem,MgQLayerItem *layer)
{
  	model_->resetLayers(sceneItem);
		
	int row=model_->layerToRow(layer);
	QModelIndex index=model_->index(row,0);
	if(index.isValid())
	{
		slotSelectLayer(index);
	}
	else
	{
		slotCheckItemStatus();
	}
	
	//Try to restore the expand state
	foreach(QModelIndex index,expandList_)
	{
		if(model_->hasChildren(index))
		{
			view_->setExpanded(index,true);
		}
	}	
	
}

void MvQLayerWidget::reset(MgQSceneItem *sceneItem)
{
	MgQLayerItem *layer=0;
	MgQLayerItem *lastLayer=0;
	
	for(int i=sceneItem->layerItems().count()-1; i >=0; i--)
	{
	  	MgQLayerItem *item=sceneItem->layerItems().at(i);
	  	lastLayer=item;
		
	  	QString str(item->layer().name().c_str());
		QStringList lst=str.split("/");
		if(!lst.isEmpty())
		{
			str=lst.last();
		}		

		if(str == lastSelectedLayerText_)
		{  
			layer=item;
		}
	}
		
	if(!layer)
	  	layer=lastLayer;
			
	//contentsLoaded_=false;
	reset(sceneItem,layer);   
	//contentsLoaded_=true;
}


int MvQLayerWidget::layerAtGlobalPos(const QPoint& p)
{
  	QPoint pv=view_->mapFromGlobal(p);
  	QModelIndex index=view_->indexAt(pv);
	
	MvQLayerContentsIcon *icon=model_->indexToIcon(index);
	if(!icon)
	  	return -1;
	
	qDebug() << "name: " << icon->name();	

	return -1;
	
	//Get the dataUinitId
	/*MvIcon& dropIcon =  cl->GetIconMain ();
	Cached verbTarget = dropIcon.Request ().getVerb ();
	if ( ObjectList::IsDataUnit ( verbTarget ) == true )
	     set_value ( id->header, "_CONTENTS_DATAUNIT_ID", "%d", dropIcon.Id());*/
	
	/*if(index.isValid())
	{
	  	MgQLayerItem *layer=model_->rowToLayer(index.row());
		if(layer)
		{
		  	QString str(layer->layer().name().c_str());
		} 
	}
	
	qDebug() << "layer drop index" << index;
  	*/
}










/*

#include <QButtonGroup>
#include <QDebug>
#include <QLabel>
#include <QListWidget>
#include <QHBoxLayout>
#include <QPainter>
#include <QStackedLayout>
#include <QToolButton>
#include <QVBoxLayout>

#include "MgQSceneItem.h"

#include "MvQLayerWidget.h"
#include "MvQLayerWidget.h"
#include "MvQLayerDataWidget.h"
#include "MvQLayerMetaDataWidget.h"

MvQLayerWidget::MvQLayerWidget(MgQPlotScene *scene,MvQPlotView *plotView,QWidget *parent) : QWidget(parent), sceneItem_(0)
{
  	contentsLoaded_=false;
	metaLoaded_=false;
	dataLoaded_=false;
	layerListLoaded_=false;	
	
	QVBoxLayout *layout = new QVBoxLayout;
	layout->setContentsMargins(0,0,0,0);
	setLayout(layout);
	
	//Top row
	QHBoxLayout *hb = new QHBoxLayout;
	layout->addLayout(hb);
	
	showLayerTb_ = new QToolButton(this);
	showLayerTb_->setToolTip(tr("View layers"));
	showLayerTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/layers.svg")));
	showLayerTb_->setCheckable(true);
	showLayerTb_->setChecked(true);
	hb->addWidget(showLayerTb_);

	//connect(showLayerTb_,SIGNAL(toggled(bool)),
	//	this,SLOT(slotLayerMeta(bool)));
	
	showMetaTb_ = new QToolButton(this);
	showMetaTb_->setToolTip(tr("View meta-data"));
	showMetaTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/meta_data.svg")));
	showMetaTb_->setCheckable(true);
	showMetaTb_->setChecked(false);
	hb->addWidget(showMetaTb_);
	//hb->addStretch(1);
	
	//connect(showLayerTb_,SIGNAL(toggled(bool)),
	//	this,SLOT(slotLayerMeta(bool)));
	
	showDataTb_ = new QToolButton(this);
	showDataTb_->setToolTip(tr("View data"));
	showDataTb_->setIcon(QPixmap(QString::fromUtf8(":/uPlot/meta_data.svg")));
	showDataTb_->setCheckable(true);
	showDataTb_->setChecked(false);
	hb->addWidget(showDataTb_);
	hb->addStretch(1);

	//connect(showMetaTb_,SIGNAL(toggled(bool)),
	//	this,SLOT(slotShowMeta(bool)));
	
	showBg_=new QButtonGroup(this);
	showBg_->setExclusive(true);
	showBg_->addButton(showLayerTb_,0);
	showBg_->addButton(showMetaTb_,1);
	showBg_->addButton(showDataTb_,2);

	connect(showBg_,SIGNAL(buttonClicked(int)),
		this,SLOT(slotShowContents(int)));
				
	//----------------------
	// Layer selector list	
	//----------------------
	
	hb=new QHBoxLayout;
	layout->addLayout(hb);
	
	layerList_=new QListWidget;
	layerList_->setViewMode(QListView::IconMode);
	layerList_->setFlow(QListView::LeftToRight);
	layerList_->setMovement(QListView::Static);
	layerList_->setWrapping(false);
    	layerList_->setIconSize(QSize(48, 48));
	layerList_->setMaximumHeight(75);
     	layerList_->setSpacing(5);
	hb->addWidget(layerList_);

	connect(layerList_,SIGNAL(itemActivated(QListWidgetItem*)),
		this,SLOT(slotSelectLayerFromList(QListWidgetItem*)));
		
	layerList_->hide();
	
	//----------------------
	// Central
	//----------------------
	
	centralLayout_=new QStackedLayout;
	layout->addLayout(centralLayout_,1);

	//----------------------
	// ContentsWidget	
	//----------------------
	
	contentsWidget_=new MvQLayerWidget(scene);
	centralLayout_->addWidget(contentsWidget_);
			
	//----------------------
	// Metadata widget
	//----------------------
	
	metaWidget_=new MvQLayerMetaDataWidget();
	centralLayout_->addWidget(metaWidget_);	
	
	//----------------------
	// Data widget
	//----------------------
	
	dataWidget_=new MvQLayerDataWidget(scene,plotView);
	centralLayout_->addWidget(dataWidget_);		
						
}


MvQLayerWidget::~MvQLayerWidget()
{
}

MgQLayerItem* MvQLayerWidget::currentLayerFromList()
{	
  	QListWidgetItem *item=layerList_->currentItem();
	if(!item)
	{  
		return 0;
	}  
	
	int layerIndex=item->data(Qt::UserRole).toInt();
	if( layerIndex >=0 &&  layerIndex < sceneItem_->layerItems().count())
	{  
		return sceneItem_->layerItems().at(layerIndex);
	}
	else
	{
	  	return 0;
	}	
}

void MvQLayerWidget::setCurrentItemForLayerList(MgQLayerItem* item)
{	
	if(!item)
  		return;
	
	int layerIndex= sceneItem_->layerItems().indexOf(item);
	if(layerIndex != -1)
	{
		for(int i=0; i < layerList_->count(); i++)
		{
	  		if(layerList_->item(i)->data(Qt::UserRole).toInt() == layerIndex)
			{
		  		layerList_->setCurrentRow(i,QItemSelectionModel::SelectCurrent);
				break;
			}
		}
	}	
}	
	

void MvQLayerWidget::slotShowContents(int id)
{
	MgQLayerItem* layer;
	int currentId=centralLayout_->currentIndex();
	
	if(currentId == 0)
	{
		layer=contentsWidget_->currentLayer(); 				
	}
	else
	{
	  	layer=currentLayerFromList();	
	}  
	
      	if(id == 0)	
	{
		if(!contentsLoaded_)
		{
		  	contentsWidget_->layersAreAboutToChange();
			contentsWidget_->reset(sceneItem_,layer);
			contentsLoaded_=true;
		}
		else
		{
		  	contentsWidget_->slotSelectLayer(layer);		  		  
		}  
		layerList_->hide();
	}	
	else
	{
		//We need to do it all the time to pick up the current layer stacking order
		resetLayerList(sceneItem_,layer);
		layerListLoaded_=true;
		
		
		layerList_->show();
		
		if(id == 1)
		{
		  	if(!metaLoaded_)
			{
			  	metaWidget_->reset(sceneItem_,layer);	
				metaLoaded_=true;
			}
			else
			{  
				metaWidget_->setLayer(layer);
			}
		}
		else if(id == 2)
		{
		  	if(!dataLoaded_)
			{
			  	dataWidget_->reset(sceneItem_,layer);	
				dataLoaded_=true;
			}
			else
			{  
				dataWidget_->setLayer(layer);
			}
		}
		
	}	
								
  	centralLayout_->setCurrentIndex(id);  
}  


void MvQLayerWidget::slotFrameChanged()
{
  	switch(centralLayout_->currentIndex())
	{
	case 1:
	  	metaWidget_->slotFrameChanged(); 
		break;
	case 2:
	  	dataWidget_->slotFrameChanged(); 
		break;
	default:
	  	break;
	}
}

void  MvQLayerWidget::slotSelectLayerFromList(QListWidgetItem* )
{  	
  	int currentId=centralLayout_->currentIndex();
	switch(currentId)
	{
	case 1:	
		metaWidget_->setLayer(currentLayerFromList());	  
		break;
	case 2:	
		dataWidget_->setLayer(currentLayerFromList());	  
		break;
	default:
	  	break;
	}  
}  


void MvQLayerWidget::layersAreAboutToChange()
{
	switch(centralLayout_->currentIndex())
	{
	case 0:
		lastSelectedLayerText_=contentsWidget_->currentLayerText();
		contentsWidget_->layersAreAboutToChange();
		break;
	case 1:
	  	if(layerList_->currentItem())
		{
		  	lastSelectedLayerText_=layerList_->currentItem()->text();
		}
		break;
	case 2:
	  	if(layerList_->currentItem())
		{
		  	lastSelectedLayerText_=layerList_->currentItem()->text();
		}
		break;			
	default:
	  	break;
	}
}

void MvQLayerWidget::reset(MgQSceneItem *sceneItem)
{
	sceneItem_=sceneItem;
	
	MgQLayerItem *layer=0;
	MgQLayerItem *lastLayer=0;
	
	for(int i=sceneItem_->layerItems().count()-1; i >=0; i--)
	{
	  	MgQLayerItem *item=sceneItem_->layerItems().at(i);
	  	lastLayer=item;
		
	  	QString str(item->layer().name().c_str());
		QStringList lst=str.split("/");
		if(!lst.isEmpty())
		{
			str=lst.last();
		}		

		if(str == lastSelectedLayerText_)
		{  
			layer=item;
		}
	}
		
	if(!layer)
	  	layer=lastLayer;
	
	
	int currentId=centralLayout_->currentIndex();
	
	//reset widget load states
	contentsLoaded_=false;
	metaLoaded_=false;
	dataLoaded_=false;
	layerListLoaded_=false;	

	switch(currentId)
	{
	case 0:
	  	contentsWidget_->reset(sceneItem,layer);   
		contentsLoaded_=true;
		break;
	case 1:	
	  	contentsWidget_->reset(0,0); 
		
		resetLayerList(sceneItem,layer);
		metaWidget_->reset(sceneItem,layer);		
		metaLoaded_=true;
		layerListLoaded_=true;	
		break;
	case 2:	
	  	contentsWidget_->reset(0,0); 
		
		resetLayerList(sceneItem,layer);
		dataWidget_->reset(sceneItem,layer);		
		dataLoaded_=true;
		layerListLoaded_=true;	
	
	default:
	  	break;
	}	
}

//Update layer selector
void MvQLayerWidget::resetLayerList(MgQSceneItem *sceneItem, MgQLayerItem* layer)
{
	layerList_->clear();
	
	if(!sceneItem)
	  	return;
	
	std::map<int,int> stackLevel;
	for(int i=0; i < sceneItem->layerItems().count(); i++)
	{
		stackLevel[sceneItem->layerItems().at(i)->stackLevel()]=i;
	}
	
	//Check is needed!!
		
	for(int i=sceneItem->layerItems().count()-1; i >=0; i--)
	{
	//  	MgQLayerItem *item=sceneItem->layerItems().at(i);
	  	
		MgQLayerItem *item=sceneItem->layerItems().at(stackLevel[i]);	

		QString str(item->layer().name().c_str());
		QStringList lst=str.split("/");
		if(!lst.isEmpty())
		{
			str=lst.last();
		}		

		QPixmap pix=QPixmap::fromImage(item->preview().scaled(QSize(48,48),Qt::KeepAspectRatio));
		QPainter painter(&pix);
		painter.setPen(QColor(230,230,230));
		painter.drawRect(pix.rect().adjusted(1,1,-1,-1));
			
		QListWidgetItem *lstItem=new QListWidgetItem(pix,str);
		lstItem->setData(Qt::UserRole,stackLevel[i]); // We store the real index 
		layerList_->addItem(lstItem);		
	}
	
	setCurrentItemForLayerList(layer);
}

int MvQLayerWidget::layerAtGlobalPos(const QPoint& p)
{
  	if(centralLayout_->currentIndex() == 0)
	{  
		return contentsWidget_->layerAtGlobalPos(p);	  	
	}
	return -1;
}	

void MvQLayerWidget::writeSettings(QSettings& settings)
{
  	settings.beginGroup("MvQLayerWidget");
  
	settings.setValue("id",centralLayout_->currentIndex());
	settings.setValue("histoEnabled",metaWidget_->isHistoEnabled());
	settings.setValue("histoVisdefIndex",metaWidget_->histoVisdefCurrentIndex());
	settings.setValue("statsEnabled",metaWidget_->isStatsEnabled());
	
	settings.endGroup();
	
}

void MvQLayerWidget::readSettings(QSettings& settings)
{
  	settings.beginGroup("MvQLayerWidget");
	
	QVariant val;
	
	val=settings.value("id");	
	QAbstractButton *tb=showBg_->button((val.isNull())?0:val.toInt());
	if(tb)
	  	tb->click();
	else
		showBg_->button(0)->click();
	
	val=settings.value("histoEnabled");
	metaWidget_->setHistoEnabled((val.isNull())?true:val.toBool());
	
	val=settings.value("histoVisdefIndex");
	metaWidget_->setHistoVisdefInitialIndex((val.isNull())?0:val.toInt());
	
	val=settings.value("statsEnabled");
	metaWidget_->setStatsEnabled((val.isNull())?true:val.toBool());

  	settings.endGroup();
  
}  

*/
