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

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QInputDialog>
#include <QMessageBox>
#include <QToolButton>
#include <QTabBar>
#include <QStackedWidget>

#include "MvQFolderDrawerPanel.h"

#include "MvQContextMenu.h"
#include "MvQDrawerView.h"
#include "MvQFolderModel.h"

#include "Folder.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "IconObject.h"

MvQFolderDrawerPanel::MvQFolderDrawerPanel(QWidget *parent) : MvQDrawerPanel(parent)
{   
  	//Init
	parentFolder_=Folder::folder("stationary");
	if(parentFolder_)
	{
		parentFolder_->scan();
		
		const map<string,IconObjectH>& kids= parentFolder_->kids();
		for(map<string,IconObjectH>::const_iterator it=kids.begin(); it != kids.end(); it++)
		{						
			IconObject *obj=it->second;
			if(it->second->isFolder())
			{
			  	Folder *folder=static_cast<Folder*>(obj);
				createDrawer(folder);		
			}
		}
		
		parentFolder_->addObserver(this);
		
	}	
	
	//Add cornerbutton
	QToolButton *tb=new QToolButton(this);
	tb->setIcon(QPixmap(QString::fromUtf8(":/desktop/add_drawer.svg")));
	tb->setAutoRaise(true);
	tb->setToolTip(tr("Add new drawer"));
	addCornerButton(tb);
	
	//Selection
	connect(tb,SIGNAL(clicked(bool)),
		this,SLOT(slotCreateDrawer(bool)));
}		

MvQFolderDrawerPanel::~MvQFolderDrawerPanel()
{
	parentFolder_->removeObserver(this);
}

MvQContextItemSet* MvQFolderDrawerPanel::cmSet()
{
	static MvQContextItemSet cmItems("FolderDrawerPanel");  
  	return &cmItems;
}

void MvQFolderDrawerPanel:: setIconPositions()
{
	/*for(int i=0; i < tab_->count(); i++)
	{
	  	MvQDrawerView* view  =static_cast<MvQDrawerView*>(stacked_->widget(i));	
		if(view)
		  	view->slotSetPositions();
	}*/	 
}

//---------------------
// 
//---------------------

void MvQFolderDrawerPanel::createDrawer(Folder *folder)
{
	MvQFolderModel *model=new MvQFolderModel(this);
	model->setFolder(folder);
  
  	MvQDrawerView *drawer = new MvQDrawerView(model);
	MvQDrawerPanel::addDrawer(drawer,QString::fromStdString(folder->name()));	
	//drawer->setHelper(true);
		
	connect(drawer,SIGNAL(itemEntered(QString)),
		this,SIGNAL(itemEntered(QString)));
			
	connect(drawer,SIGNAL(desktopCommandRequested(QString,QPoint)),
	        this,SLOT(slotCommandFromView(QString,QPoint)));	
		
}


//==============================================
//
// Context menu + button actions
//
//===============================================

void MvQFolderDrawerPanel::slotCreateDrawer(bool)
{
	string offeredName=getUniqueName("Drawer");
	  
	bool ok;
     	QString text = QInputDialog::getText(0, 
			tr("Create new drawer"),
                        tr("Drawer name:"), QLineEdit::Normal,
                        QString::fromStdString(offeredName), &ok);		
	
	if(!ok || text.isEmpty())
        	return; 	
				
	string name=text.toStdString();
		
	parentFolder_=Folder::folder("stationary");
	if(!parentFolder_)
		return;
	
	const IconClass &kind=IconClass::find("FOLDER");	
	IconFactory::create(parentFolder_,name,kind);
}  

void MvQFolderDrawerPanel::renameDrawer(int index)
{
  	if(index<0 || index >= drawerCount())
		return;
		  
	bool ok;
     	QString text = QInputDialog::getText(0, 
		tr("Rename drawer"),
                tr("Drawer name:"), QLineEdit::Normal,
                drawerText(index), &ok);		
	
	if(ok && !text.isEmpty())
        { 	
		Folder *folder=indexToFolder(index);		
		string name=getUniqueName(text.toStdString());
		if(folder)
			folder->rename(name);
	}
}  

void MvQFolderDrawerPanel::deleteDrawer(int index)
{
	if(index < 0 || index >= drawerCount())
  		return;	
	
  	if(QMessageBox::question(0,tr("Delete drawer"),tr("Do you want to delete drawer") +" <b>" + drawerText(index) + "</b>?",
			     QMessageBox::Yes | QMessageBox::Cancel,QMessageBox::Cancel) == QMessageBox::Cancel)
	{
	  	return;
	}	
		
	Folder *folder=indexToFolder(index);
	if(folder)
		folder->toWastebasket();
}  


//----------------------------------------------
// Observer methods
//----------------------------------------------

void MvQFolderDrawerPanel::arrived(IconObject *obj)
{
	Folder *folder=static_cast<Folder*>(obj);
	if(!folder)
	  	return;
	
	createDrawer(folder); 
}  

void MvQFolderDrawerPanel::renamed(IconObject *obj,const string&)
{
	Folder *folder=static_cast<Folder*>(obj);
	if(!folder)
	  	return;
	
	MvQDrawerPanel::renameDrawer(folderToIndex(folder),QString::fromStdString(folder->name()));
}  

void MvQFolderDrawerPanel::gone(IconObject *obj)
{
	Folder *folder=static_cast<Folder*>(obj);
	if(!folder)
	  	return;
		
	int index=folderToIndex(folder);
	MvQFolderModel *model=indexToModel(index);
	
	MvQDrawerPanel::deleteDrawer(folderToIndex(folder));
	
	if(model)
	  	delete model;
}  

//----------------------------------------------
// Context menu
//----------------------------------------------

void MvQFolderDrawerPanel::command(QString name,int index)
{
	if(name == "deleteDrawer")
	{
	  	deleteDrawer(index);
	}
	else if(name == "renameDrawer")
	{
	  	renameDrawer(index);
	}
}  

//Desktop menu signal from one of the views
void MvQFolderDrawerPanel::slotCommandFromView(QString name,QPoint /*pos*/)
{
	if(name == "deleteDrawer" || name == "renameDrawer")
	{    
		MvQDrawerView *view=static_cast<MvQDrawerView*>(sender());
		if(!view)
			return;
	
		int index=drawerIndex(view);
		if(index != 0)
		  	command(name,index);	
	}	  		
} 
	

string MvQFolderDrawerPanel::getUniqueName(const string& name)
{
	Folder* folder=Folder::folder("stationary");
	if(folder)
	{
		return folder->uniqueName(name);
	}
	return string(name);  
}  

int MvQFolderDrawerPanel::folderToIndex(Folder *f)
{
  	for(int i=0; i < drawerCount(); i++)
	{
	  	MvQDrawerView *view=static_cast<MvQDrawerView*>(drawer(i));
		
		if(view->currentFolder() == f)
		  	return i;
	}
	
	return -1;
}

Folder *MvQFolderDrawerPanel::indexToFolder(int index)
{ 	
	MvQDrawerView *view=static_cast<MvQDrawerView*>(drawer(index));		
	return (view)?view->currentFolder():0;
}	

MvQFolderModel *MvQFolderDrawerPanel::indexToModel(int index)
{
  	MvQDrawerView *view=static_cast<MvQDrawerView*>(drawer(index));
	return (view)?view->folderModel():0;
}
