/***************************************************************************
 *   Copyright (C) 2007  Martin Meredith                                   *
 *   mez@ubuntu.com                                                        *
 *                                                                         *
 *   Copyright (C) 2005 by Joe Ferris                                      *
 *   jferris@optimistictech.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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

#include <tdeapplication.h>
#include <tdeconfig.h>
#include <tdeparts/componentfactory.h>
#include <tdelocale.h>

#include <tqstring.h>
#include <tqstringlist.h>
 
#include "katapultsettings.h"
#include "katapultcatalog.h"
#include "katapultconfigdlg.h"
#include "katapultdisplay.h"
#include "actionregistry.h"

KatapultSettings::KatapultSettings()
{
	_forceWrite = false;
	readSettings();
	_isConfiguring = false;
	_activeCatalogs.setAutoDelete(true);
	_display = 0;
	
	loadCatalogPlugins();
	loadDisplayPlugins();
}


KatapultSettings::~KatapultSettings()
{
	if (_forceWrite)
		writeSettings();

	if(_display != 0)
		delete _display;
}

void KatapultSettings::readSettings()
{
	TDEConfig *config = tdeApp->config();
	_hideSessionNotification = config->readNumEntry("HideSessionNotification", 1);
	_hideUserNotification = config->readNumEntry("HideUserNotification", 0);
	_notificationTimeout = config->readNumEntry("NotificationTimeout", 5000);
	_hideDelay = config->readUnsignedNumEntry("HideDelay", 1000);
	_noResultsDelay = config->readUnsignedNumEntry("NoResultsDelay", 2500);
	_noResultsAction = (NRAction) config->readUnsignedNumEntry("NoResultsAction", NR_ClearQuery);
	_systrayIcon = config->readBoolEntry("SystrayIcon", true);
	_autoExec = config->readBoolEntry("AutoExec", false);
	_displayName = config->readEntry("Display", "Pure Display");

	TQStringList defCatalogs;
	defCatalogs << "Program Catalog" << "Bookmark Catalog" << "Document Catalog" << "Calculator Catalog" << "Amarok Catalog" << "Spell Catalog" << "Google Catalog" << "Execution Catalog";
	_activeCatalogNames = config->readListEntry("Catalogs", defCatalogs);

	// Force a config write if notification is to be shown once.
	// (in writeSettings(), _hideSessionNotification or _hideUserNotification
	// is changed before writing [if necessary]).
	_forceWrite = ((tdeApp->isSessionRestored() && _hideSessionNotification == 1) ||
			(!tdeApp->isSessionRestored() && _hideUserNotification == 1));
}

void KatapultSettings::writeSettings()
{
	TDEConfig *config = tdeApp->config();
	int hideSession = _hideSessionNotification;
	int hideUser = _hideUserNotification;

	// If notification had to be shown once, set it to hide always.
	if (tdeApp->isSessionRestored()) {
		if (hideSession == 1) hideSession = 2;
	} else {
		if (hideUser == 1) hideUser = 2;
	}

	config->writeEntry("HideSessionNotification", hideSession);
	config->writeEntry("HideUserNotification", hideUser);
	config->writeEntry("NotificationTimeout", _notificationTimeout);
	config->writeEntry("HideDelay", _hideDelay);
	config->writeEntry("NoResultsDelay", _noResultsDelay);
	config->writeEntry("NoResultsAction", (int) _noResultsAction);
	config->writeEntry("SystrayIcon", _systrayIcon);
	config->writeEntry("AutoExec", _autoExec);
	config->writeEntry("Catalogs", _activeCatalogNames);
	config->writeEntry("Display", _displayName);

	TQDictIterator<KatapultCatalog> it(_activeCatalogs);
	KatapultCatalog *catalog;
	while((catalog = it.current()) != 0)
	{
		TDEConfigGroup group(config, TQString("Catalogs/%1").arg(it.currentKey()));
		catalog->writeSettings(&group);
		++it;
	}
	
	if(_display != 0)
	{
		TDEConfigGroup group(config, TQString("Displays/%1").arg(_displayName));
		_display->writeSettings(&group);
	}

	config->sync();
}

void KatapultSettings::configure()
{
	if(!_isConfiguring)
	{
		_isConfiguring = true;
		
		KatapultConfigDlg *dlg = new KatapultConfigDlg(this);
		if(dlg->exec() == TQDialog::Accepted) {
			writeSettings();
			emit systrayChanged();
			loadCatalogPlugins();
			emit catalogsChanged();
			
		} else {
			readSettings();
			loadCatalogPlugins();
			loadDisplayPlugins();
			emit catalogsChanged();
			emit displayChanged();
		}
		delete dlg;
		
		_isConfiguring = false;
	}
}

bool KatapultSettings::isConfiguring() const
{
	return _isConfiguring;
}

bool KatapultSettings::isAutoExecute() const
{
	return _autoExec;
}

void KatapultSettings::setAutoExecute(bool _autoExec)
{
	this->_autoExec = _autoExec;
}

int KatapultSettings::hideDelay() const
{
	return _hideDelay;
}

void KatapultSettings::setHideDelay(int _hideDelay)
{
	this->_hideDelay = _hideDelay;
}

int KatapultSettings::noResultsDelay() const
{
	return _noResultsDelay;
}

void KatapultSettings::setNoResultsDelay(int _noResultsDelay)
{
	this->_noResultsDelay = _noResultsDelay;
}

KatapultSettings::NRAction KatapultSettings::noResultsAction() const
{
	return _noResultsAction;
}

void KatapultSettings::setNoResultsAction(NRAction _noResultsAction)
{
	this->_noResultsAction = _noResultsAction;
}

bool KatapultSettings::systrayIcon() const
{
	return _systrayIcon;
}

void KatapultSettings::setSystrayIcon(bool _systrayIcon)
{
	this->_systrayIcon = _systrayIcon;
}

bool KatapultSettings::hideNotification() const
{
	int hide = tdeApp->isSessionRestored() ? _hideSessionNotification : _hideUserNotification;
	return (hide != 0 && hide != 1);
}

int KatapultSettings::notificationTimeout() const
{
	return _notificationTimeout;
}

TQString KatapultSettings::displayName() const
{
	return _displayName;
}

TQStringList KatapultSettings::displayNames() const
{
	return _displayNames;
}

TQStringList KatapultSettings::displayIds() const
{
	return _displayIds;
}

int KatapultSettings::displayNumber() const
{
	return _displayIds.findIndex(_displayName);
}

KatapultDisplay * KatapultSettings::display() const
{
	return _display;
}

void KatapultSettings::setDisplayName(TQString name)
{
	_displayName = name;
	loadDisplayPlugins();
	emit displayChanged();
}

TQStringList KatapultSettings::catalogNames() const
{
	return _catalogNames;
}

TQStringList KatapultSettings::catalogIds() const
{
	return _catalogIds;
}

TQStringList KatapultSettings::activeCatalogNames() const
{
	return _activeCatalogNames;
}

TQStringList KatapultSettings::inactiveCatalogNames() const
{
	TQStringList inactiveCatalogs, catalogs = _catalogIds;
	for(TQStringList::Iterator it = catalogs.begin(); it != catalogs.end(); ++it)
	{
		if(!_activeCatalogNames.contains(*it))
			inactiveCatalogs.append(*it);
	}
	return inactiveCatalogs;
}

TQDict<KatapultCatalog> KatapultSettings::activeCatalogs() const
{
	return _activeCatalogs;
}

void KatapultSettings::activateCatalog(TQString catalogName)
{
	_activeCatalogNames.append(catalogName);
	loadCatalogPlugins();
	emit catalogsChanged();
}

void KatapultSettings::deactivateCatalog(TQString catalogName)
{
	_activeCatalogNames.remove(catalogName);
	loadCatalogPlugins();
	emit catalogsChanged();
}

void KatapultSettings::loadCatalogPlugins()
{
	_activeCatalogs.clear();
	_catalogNames.clear();
	_catalogIds.clear();
	ActionRegistry::self()->clear();

	TDETrader::OfferList offers = TDETrader::self()->query("Katapult/Catalog");
	TDETrader::OfferList::ConstIterator it;
	for(it = offers.begin(); it != offers.end(); ++it)
	{
		TQString id;
		
		KService::Ptr service = *it;
		KatapultCatalog *catalog;
		
		if(!service->property("X-Katapult-ID", TQVariant::String).toString().isEmpty())
			id = service->property("X-Katapult-ID", TQVariant::String).toString();
		else
			id = service->name();
		
		_catalogNames.append(service->name());
		_catalogIds.append(id);
		
		if(_activeCatalogNames.contains(id))
		{
			int errCode = 0;
			catalog = KParts::ComponentFactory::createInstanceFromService<KatapultCatalog>
				(service, 0, 0, TQStringList(), &errCode);
			if(catalog != 0)
			{
				TDEConfigGroup group(tdeApp->config(), TQString("Catalogs/%1").arg(id));
				catalog->readSettings(&group);
				catalog->initialize();
				_activeCatalogs.insert(id, catalog);
			}
		}
	}
}

void KatapultSettings::loadDisplayPlugins()
{
	if(_display != 0)
	{
		delete _display;
		_display = 0;
	}
	
	_displayNames.clear();
	_displayIds.clear();
	
	TDETrader::OfferList offers = TDETrader::self()->query("Katapult/Display");
	TDETrader::OfferList::ConstIterator it;
	for(it = offers.begin(); it != offers.end(); ++it)
	{
		KService::Ptr service = *it;
		
		_displayNames.append(service->name());
		if(!service->property("X-Katapult-ID", TQVariant::String).toString().isEmpty())
			_displayIds.append(service->property("X-Katapult-ID", TQVariant::String).toString());
		else
			_displayIds.append(service->name());

		if(_displayIds.last() == _displayName)
		{
			int errCode = 0;
			_display = KParts::ComponentFactory::createInstanceFromService<KatapultDisplay>
				(service, 0, 0, TQStringList(), &errCode);
		}
	}
	if(_display != 0)
	{
		TDEConfigGroup group(tdeApp->config(), TQString("Displays/%1").arg(_displayName));
		_display->readSettings(&group);
	}
}

KatapultCatalog * KatapultSettings::catalog(TQString catalogName) const
{
	return _activeCatalogs.find(catalogName);
}

#include "katapultsettings.moc"
