/***************************************************************************
                          devicepopupmenu.cpp  -  description
                             -------------------
    begin                : lun aoû 4 2003
    copyright            : (C) 2003 by ervin
    email                : ervin at tuxfamily dot org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "devicepopupmenu.h"

#include <qdir.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <kmimetype.h>
#include <kiconloader.h>
#include <kglobalsettings.h>
#include <ktrader.h>
#include <kaction.h>
#include <qdatastream.h>
#include <dcopclient.h>
#include <kmessagebox.h>

#define OPEN_SERVICE 0

DevicePopupMenu::DevicePopupMenu(const KFileItem &fileItem, QWidget *parent)
	: KPopupMenu(parent, "device_popupmenu"), mFileItem(fileItem), mServicesSubMenu(0)
{
	insertTitle(mFileItem.name());

	queryMountWatcher();
	loadServices();

	insertItem(i18n("Open"), OPEN_SERVICE);
	
	int id = OPEN_SERVICE+1;
	KIconLoader loader;

	if(!mDeviceServices.isEmpty())
	{
		QValueList<KDEDesktopMimeType::Service>::Iterator it = mDeviceServices.begin();
		for( ; it != mDeviceServices.end(); ++it )
		{
			QIconSet icon = loader.loadIconSet((*it).m_strIcon, KIcon::Small, 0, true);
			insertItem(icon, (*it).m_strName, id);
			mServicesMap[id++]=*it;
		}
	}

	if(!mDirectoryServices.isEmpty() && mMounted)
	{
		KPopupMenu *menu;

		if(mDeviceServices.isEmpty())
		{
			menu = this;
		}
		else
		{
			menu = &mServicesSubMenu;
			insertItem(i18n("Services"), menu);
		}

		QValueList<KDEDesktopMimeType::Service>::Iterator it = mDirectoryServices.begin();
		for( ; it != mDirectoryServices.end(); ++it )
		{
			QIconSet icon = loader.loadIconSet((*it).m_strIcon, KIcon::Small, 0, true);
			menu->insertItem(icon, (*it).m_strName, id);
			mServicesMap[id++]=*it;
		}
	}

	connect(this, SIGNAL( activated(int) ), this, SLOT( slotRunService(int) ));
	connect(&mServicesSubMenu, SIGNAL( activated(int) ), this, SLOT( slotRunService(int) ));
}

DevicePopupMenu::~DevicePopupMenu()
{
	
}

void DevicePopupMenu::queryMountWatcher()
{
	QByteArray data;
	QByteArray param;
	QCString retType;
	QStringList retVal;
	QDataStream streamout(param,IO_WriteOnly);
	streamout<<mFileItem.url().fileName();

	DCOPClient *client = kapp->dcopClient();

	if(client->call("kded", "mountwatcher", "basicDeviceInfo(QString)",
	                param,retType,data,false )
	  )
	{
		QDataStream streamin(data,IO_ReadOnly);
		streamin>>retVal;

		mMountPoint = KURL(retVal[2]);
		mMounted = retVal[4]=="true";
	}
}

void DevicePopupMenu::loadServices()
{
	QStringList dirs = KGlobal::dirs()->findDirs("data", "konqueror/servicemenus/");
	QStringList::ConstIterator dIt = dirs.begin();
	QStringList::ConstIterator dEnd = dirs.end();

	for(; dIt != dEnd; ++dIt)
	{
		QDir dir(*dIt);

		QStringList entries = dir.entryList(QDir::Files);
		QStringList::ConstIterator eIt = entries.begin();
		QStringList::ConstIterator eEnd = entries.end();

		for(; eIt != eEnd; ++eIt)
		{
			KSimpleConfig cfg(*dIt+*eIt, true);
			cfg.setDesktopGroup();

			if(cfg.hasKey("X-KDE-AuthorizeAction"))
			{
				bool ok = true;
				QStringList list = cfg.readListEntry("X-KDE-AuthorizeAction");

				if(kapp && !list.isEmpty())
				{
					for(QStringList::ConstIterator it = list.begin();
					    it != list.end();
					    ++it)
					{
						if (!kapp->authorize((*it).stripWhiteSpace()))
						{
							ok = false;
							break;
						}
					}
				}

				if(!ok) continue;
			}

			if(cfg.hasKey( "Actions" ) && cfg.hasKey( "ServiceTypes" ))
			{
				QStringList types = cfg.readListEntry("ServiceTypes");
				if( types.contains(mFileItem.mimetype()) )
				{
					mDeviceServices += KDEDesktopMimeType::userDefinedServices(*dIt+*eIt, true);
				}
				else if( types.contains("inode/directory") )
				{
					mDirectoryServices += KDEDesktopMimeType::userDefinedServices(*dIt+*eIt, true);
				}
			}
		}
	}
}


bool operator==(const KDEDesktopMimeType::Service &a, const KDEDesktopMimeType::Service &b)
{
	return a.m_strName==b.m_strName
	    && a.m_strIcon==b.m_strIcon
	    && a.m_strExec==b.m_strExec
	    && a.m_type==b.m_type
	    && a.m_display==b.m_display;
}

void DevicePopupMenu::slotRunService(int id)
{
	if(id==OPEN_SERVICE)
	{
		mFileItem.run();
		return;
	}
	
	KDEDesktopMimeType::Service service = mServicesMap[id];
	KURL url = mMountPoint;

	if(mDeviceServices.contains(service))
	{
		url = mFileItem.url();
	}

	KDEDesktopMimeType::executeService(url, service);
}

#include "devicepopupmenu.moc"
