/***************************************************************************
 *   Copyright (C) 2004 by Stefano                                         *
 *   stefano@xiaprojects.com                                               *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "xeplugin_command.h"

#include "xeconfiguration.h"
#include "xgdocker.h"

#include "taskmanager.h"

#include <kpopupmenu.h>
#include <kiconloader.h> 
#include <krun.h>

#include <qcursor.h> 
#include <qvaluelist.h> 


XEPlugin_Command::XEPlugin_Command(QObject *parent, const char *name)
 : QObject(parent, name)
{
	XEObject::xPluginAdd(this);

}


XEPlugin_Command::~XEPlugin_Command()
{
}


#include "xeplugin_command.moc"


/*!
    \fn XEPlugin_Command::xEventMouseClick(int icon, int x, int y, int button)
 */
void XEPlugin_Command::xEventMouseClick(int icon, int x, int y, int button)
{
	char pippo[50];
	sprintf(pippo,"MouseClick: [%d][%d][%d]",x,y,button);
	qWarning(pippo);
	if(button==Qt::LeftButton)
	{
		if(icon>=0 && icon <ActiveConfiguration->ObjectsIcons.count())
		{
			if(ActiveConfiguration->ObjectsIcons.at(icon)->Tasks.TaskInfo!=NULL)
			{
				Task *t=(Task *)ActiveConfiguration->ObjectsIcons.at(icon)->Tasks.TaskInfo;
				t->activateRaiseOrIconify();
			}
			else
			{
			qWarning(ActiveConfiguration->ObjectsIcons.at(icon)->Actions.onClickExec);
			KRun::runCommand(ActiveConfiguration->ObjectsIcons.at(icon)->Actions.onClickExec);
			}
		}
	}
	
	if(button==Qt::RightButton)
	{
		if(icon>=0 && icon <ActiveConfiguration->ObjectsIcons.count())
		{
//			if(ActiveConfiguration->ObjectsIcons.at(icon)->Tasks.TaskInfo!=NULL)
			{
			lastIconExec=ActiveConfiguration->ObjectsIcons.at(icon)->Actions.onClickExec;
			// TODO: make 1 var only
			lastIcon=ActiveConfiguration->ObjectsIcons.at(icon);
			popMenu(
				&ActiveConfiguration->ObjectsIcons.at(icon)->Tasks
				);
				/*
				Task *t=(Task *)ActiveConfiguration->ObjectsIcons.at(icon)->Tasks.TaskInfo;
				t->activateRaiseOrIconify();
				*/
				//xEventReset(x,y);
				xGDocker->xRestore();
			}
//			else
//			{
			//qWarning(ActiveConfiguration->ObjectsIcons.at(icon)->Actions.onClickExec);
			//KRun::runCommand(ActiveConfiguration->ObjectsIcons.at(icon)->Actions.onClickExec);
//			}
		
		}
	}	
	
	if(button==Qt::MidButton)
	{
		if(icon>=0 && icon <ActiveConfiguration->ObjectsIcons.count())
		{
			// Multigroup parser
			clickMiddle(icon);
		}
	}
	
}


/*!
    \fn XEPlugin_Command::xStart()
 */
void XEPlugin_Command::xStart()
{
	qWarning("Command::xStart");
	connect(xGDocker,SIGNAL(xEventMouseClick(int,int,int,int)),
		this,SLOT(xEventMouseClick(int,int,int,int)));
	connect(xGDocker,SIGNAL(xEventMouseWheel(int,int,int,int)),
		this,SLOT(xEventMouseWheel(int,int,int,int)));
}


/*!
    \fn XEPlugin_Command::xSetup()
 */
void XEPlugin_Command::xSetup()
{
	qWarning("Mouse::xSetup");
	XEConfiguration *Configurator=(XEConfiguration *)XEObject::xGetConfiguration();
	xGDocker=(XGDocker *)XEObject::xGetDocker();
	if(Configurator==NULL || xGDocker==NULL)
	{
#ifndef ENABLE_FINAL
	// Emits Signal of warning
	//xWarningMsg(this,"error while searching for plugin");
	qWarning("error while searching for plugin");
#endif
		return;
	}
	ActiveConfiguration=Configurator->xGetConfiguration();

}


/*!
    \fn XEPlugin_Command::xStop()
 */
void XEPlugin_Command::xStop()
{
    /// @todo implement me
}


/*!
    \fn XEPlugin_Command::xEventMouseWheel(int,int,int,int)
 */
void XEPlugin_Command::xEventMouseWheel(int icon, int x, int y, int button)
{
    /// @todo implement me
	char pippo[50];
	sprintf(pippo,"MouseWheel: [%d][%d][%d]",x,y,button);
	qWarning(pippo);
	if(icon>=0 && icon <ActiveConfiguration->ObjectsIcons.count())
	{
	
		QPtrList<XSGObjectIcon> RollingList;
		int lastIndex=0;
		for(int k=0;k<ActiveConfiguration->RollingIcons.count();k++)
		{
			if(
				ActiveConfiguration->RollingIcons.at(k)->Info.Group
				==
				ActiveConfiguration->ObjectsIcons.at(icon)->Info.Group
			)
			 {
			 	RollingList.append(ActiveConfiguration->RollingIcons.at(k));
			 	if(ActiveConfiguration->RollingIcons.at(k)==
				 	ActiveConfiguration->ObjectsIcons.at(icon))lastIndex=RollingList.count()-1;
			 }
		}	
		if(RollingList.count()<2)return;
		if(button==1)
		{
			lastIndex++;
		}
		if(button==2)
		{
			lastIndex--;
			if(lastIndex<0)lastIndex=RollingList.count()-1;
		}
		lastIndex=(lastIndex)%RollingList.count();
		ActiveConfiguration->ObjectsIcons.replace(icon,RollingList.at(lastIndex));
		
		xGDocker->reloadIcon(icon);
	}
}

//#include <kicon.h> 
/*!
    \fn XEPlugin_Command::popMenu(const Task *)
 */
void XEPlugin_Command::popMenu(XSCfgTasks *Process)
{

// "launch"
// window_list.png
//"window_new.png"
	KIconLoader KDEIcons;
	// TODO: have we to clear the popup menu every time?
	if(Process->PopupMenu==NULL)
	{
		// Icon don't have the popup
		// we create new one
		Process->PopupMenu=new KPopupMenu();
		connect(Process->PopupMenu,SIGNAL(activated(int)),this,SLOT(activated(int)));
	}
//	else
	{
	Process->PopupMenu->clear();
	
	// Action menu
	Process->PopupMenu->insertTitle(KDEIcons.loadIcon("window_new",KIcon::Small),"Actions");
	Process->PopupMenu->insertItem(KDEIcons.loadIcon("launch",KIcon::Small),"Open New Window",
		this,SLOT(RunLastCmd()));
	
	for(int a=0;a<lastIcon->Actions.ActionList.count();a++)
	{
		// now supporting only exec action
		QString aAction=lastIcon->Actions.ActionList.item(a).toElement().attribute("action");
		lastIcon->Actions.ActionList.item(a).toElement().removeAttribute("MenuTmpID");
		if(aAction.isNull() || aAction=="" ||aAction=="exec")
		{
			QString aIcon=lastIcon->Actions.ActionList.item(a).toElement().attribute("image");
			if(aIcon.isNull() || aIcon=="" )aIcon="run";
			QString aInfo=lastIcon->Actions.ActionList.item(a).toElement().attribute("info");
			QString aExe=lastIcon->Actions.ActionList.item(a).toElement().attribute("data");
			if(aExe.isNull() || aExe=="" )continue;
			if(aInfo.isNull() || aInfo=="" )aInfo=aExe;
			int mID=Process->PopupMenu->insertItem(KDEIcons.loadIcon(aIcon,KIcon::Small),aInfo);
			lastIcon->Actions.ActionList.item(a).toElement().setAttribute("MenuTmpID",mID);
		}
		
	}
	
	if(lastIcon && lastIcon->PluginPopupMenu)
	{
		Process->PopupMenu->insertItem(
		KDEIcons.loadIcon("viewmag",KIcon::Small),"Plugin Actions",lastIcon->PluginPopupMenu);
	}
	//Process->PopupMenu->insertItem(KDEIcons.loadIcon("exit",KIcon::Small),"Close ALL Windows");
	//Process->PopupMenu->insertItem(KDEIcons.loadIcon("2downarrow",KIcon::Small),"Minimize ALL Windows");
	lastProcess=NULL;
	
	if(Process->Proces.count()>0)
	{
		Process->PopupMenu->insertTitle(KDEIcons.loadIcon("window_new",KIcon::Small),"Global actions");
		
		Process->PopupMenu->insertItem(
			KDEIcons.loadIcon("window_fullscreen",KIcon::Small),
			"Maximize",
			this,SLOT(maximizeAll()));
		
		Process->PopupMenu->insertItem(
			KDEIcons.loadIcon("window_nofullscreen",KIcon::Small),
			"Minimize",
			this,SLOT(minimizeAll()));
		Process->PopupMenu->insertItem(
			KDEIcons.loadIcon("remove",KIcon::Small),
			"Close",
			this,SLOT(closeAll()));
		
		Process->PopupMenu->insertTitle(KDEIcons.loadIcon("window_list",KIcon::Small),"Window list");
		lastProcess=Process;
		for(int i=0;i<Process->Proces.count();i++)
		{
			Task *ti=(Task *)Process->Proces.at(i);
			qWarning(ti->name());
			Process->PopupMenu->insertItem(ti->pixmap(),ti->name(),ti,SLOT(activateRaiseOrIconify()));
		}
	}
	Process->PopupMenu->insertTitle(KDEIcons.loadIcon("configure",KIcon::Small),"Configure");
	if(lastIcon->Info.className!="xTaskManager")
	{
	Process->PopupMenu->insertItem(KDEIcons.loadIcon("unlock",KIcon::Small),"make float",
		this,SLOT(KeepInDock()));
	}
	else
	{
	Process->PopupMenu->insertItem(KDEIcons.loadIcon("lock",KIcon::Small),"keep in dock",
		this,SLOT(KeepInDock()));
	
	}
	// KXDocker menu like the tray
	Process->PopupMenu->insertTitle(KDEIcons.loadIcon("kxdocker",KIcon::Small),"KXDocker");
	if(XEObject::xFindObject("xConfigurator")!=NULL)
	{
	//Process->PopupMenu->insertTitle(loadIcon("configure"),"Setup docker");
	Process->PopupMenu->insertItem(KDEIcons.loadIcon("iconthemes",KIcon::Small),"Configurator",
		XEObject::xFindObject("xConfigurator"),SLOT(xConfigure()));
	}
	if(xGDocker!=NULL)
	{
	//Process->PopupMenu->insertTitle(loadIcon("configure"),"Setup docker");
	Process->PopupMenu->insertItem(KDEIcons.loadIcon("close",KIcon::Small),"Quit",
		xGDocker,SLOT(close()));
	}
	
	Process->PopupMenu->popup(QCursor::pos());
	//Process->PopupMenu->exec(QCursor::pos());
	}
}


/*!
    \fn XEPlugin_Command::RunLastCmd()
 */
void XEPlugin_Command::RunLastCmd()
{
	qWarning(QString("Running: %1").arg(lastIconExec));
	KRun::runCommand(lastIconExec);
}

/*!
    \fn XEPlugin_Command::clickMiddle(int iconIndex)
 */
void XEPlugin_Command::clickMiddle(int icon)
{
	QPtrList<XSGObjectIcon> RollingList;
	int lastIndex=0;
	for(int k=0;k<ActiveConfiguration->RollingIcons.count();k++)
	{
		if(
			ActiveConfiguration->RollingIcons.at(k)->Info.Group
			==
			ActiveConfiguration->ObjectsIcons.at(icon)->Info.Group
		)
			{
			RollingList.append(ActiveConfiguration->RollingIcons.at(k));
			if(ActiveConfiguration->RollingIcons.at(k)==
				ActiveConfiguration->ObjectsIcons.at(icon))lastIndex=RollingList.count()-1;
			}
	}	
	if(RollingList.count()<2)return;
	
	// Ok than now we can check if you have already dropped the group
	QValueList<int> DroppedList;
	for(int dropped=0;dropped<ActiveConfiguration->ObjectsIcons.count();dropped++)
	{
		if(ActiveConfiguration->ObjectsIcons.at(icon)->Info.Group
			==
		ActiveConfiguration->ObjectsIcons.at(dropped)->Info.Group
		)
		{
			if(dropped==icon)continue;
			DroppedList.append((dropped));
		}
	}
	if(DroppedList.count()>0)
	{
		// we have to remove the others
		for(int dropme=DroppedList.count()-1;dropme>=0;dropme--)
		{
			xGDocker->iconRemove(DroppedList[(dropme)]);
		}
		return;
	}
	
	qWarning("xeplugin_command.cpp:277");
	for(int addme=0;addme<RollingList.count();addme++)
	{
		if(lastIndex==addme)continue;
		/*
		if(lastIndex>addme)
		ActiveConfiguration->ObjectsIcons.insert(icon-1,RollingList.at(addme));
		*/
		ActiveConfiguration->ObjectsIcons.insert(icon,RollingList.at(addme));
		xGDocker->xEventTaskAppend(icon);
	}
}


/*!
    \fn XEPlugin_Command::closeAll()
 */
void XEPlugin_Command::closeAll()
{
	if(lastProcess!=NULL)
	{
		qWarning("xeplugin_command.cpp:316 Closing all windows, it may crash if you have prev closed it!!!!!");
		
		for(int i=0;i<lastProcess->Proces.count();i++)
		{
			
			Task *ti=(Task *)lastProcess->Proces.at(i);
			qWarning(ti->name());
			ti->close();
		}
	}
}


/*!
    \fn XEPlugin_Command::maximizeAll()
 */
void XEPlugin_Command::maximizeAll()
{
	if(lastProcess!=NULL)
	{
		qWarning("xeplugin_command.cpp:345");
		
		for(int i=0;i<lastProcess->Proces.count();i++)
		{
			
			Task *ti=(Task *)lastProcess->Proces.at(i);
			qWarning(ti->name());
			ti->maximize();
		}
	}
}


/*!
    \fn XEPlugin_Command::minimizeAll()
 */
void XEPlugin_Command::minimizeAll()
{
	if(lastProcess!=NULL)
	{
		qWarning("xeplugin_command.cpp:365");
		
		for(int i=0;i<lastProcess->Proces.count();i++)
		{
			
			Task *ti=(Task *)lastProcess->Proces.at(i);
			qWarning(ti->name());
			ti->iconify();
		}
	}
}


/*!
    \fn XEPlugin_Command::KeepInDock()
 */
void XEPlugin_Command::KeepInDock()
{
	if(lastIcon!=NULL)
	{
		qWarning("xeplugin_command.cpp:388");
		if(lastIcon->Info.className=="xTaskManager")
		{
			lastIcon->Info.className="GIcon";
		}
		else
		{
			lastIcon->Info.className="xTaskManager";
		}
	}
}


/*!
    \fn XEPlugin_Command::xGetParameter(const QString,QString&)
 */
void XEPlugin_Command::xGetParameter(const QString,QString&)
{
    /// @todo implement me
}


/*!
    \fn XEPlugin_Command::xGetParameterList(QStringList*)
 */
void XEPlugin_Command::xGetParameterList(QStringList*)
{
    /// @todo implement me
}


/*!
    \fn XEPlugin_Command::activated(int)
 */
void XEPlugin_Command::activated(int mID)
{
	if(lastIcon)
	{
		for(int a=0;a<lastIcon->Actions.ActionList.count();a++)
		{
			// now supporting only exec action
			QString aAction=lastIcon->Actions.ActionList.item(a).toElement().attribute("action");
		if(aAction.isNull() || aAction=="" ||aAction=="exec")
		{
			int mIDMenu=QString(
				lastIcon->Actions.ActionList.item(a).toElement().attribute("MenuTmpID")
				).toInt();
			if(mID==mIDMenu)
			{
				QString aExe=lastIcon->Actions.ActionList.item(a).toElement().attribute("data");
				qWarning(QString("Running: %1").arg(aExe));
				KRun::runCommand(aExe);
				return;
			}
		}
		}	
	}
}
