/*****************************************************************

Copyright (c) 2000 Matthias Elter <elter@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <kglobal.h>
#include <kdebug.h>
#include <kconfig.h>
#include <assert.h>

#include "pluginmanager.h"
#include "container_extension.h"
#include "panel.h"

#include "extensionmanager.h"
#include "extensionmanager.moc"

ExtensionManager* ExtensionManager::the()
{
    static ExtensionManager extensionManager;
    return &extensionManager;
}

ExtensionManager::ExtensionManager()
    : QObject( 0, "ExtensionManager" )
{
}

void ExtensionManager::initialize()
{
    removeAllContainers();

    // restore extension layout or load a default layout
    KConfig* config = KGlobal::config();
    config->setGroup("General");

    if(config->hasKey("Extensions2"))
	loadContainerConfig();
    else
	defaultContainerConfig();
}

void ExtensionManager::defaultContainerConfig()
{
}

void ExtensionManager::saveContainerConfig(bool layoutOnly )
{
//    kdDebug(1210) << "ExtensionManager::saveContainerConfig()" << endl;

    KConfig *config = KGlobal::config();

    // build the extension list
    QStringList elist;

    for( QPtrListIterator<ExtensionContainer> it(_containers); it.current() ; ++it ) {
	ExtensionContainer* a = it.current();
	elist.append( a->extensionId() );
	// let the applet container write custom data fields
	if(!layoutOnly)
	    a->writeConfig();
    }

    // write extension list
    config->setGroup("General");
    config->writeEntry("Extensions2", elist);

    config->sync();
}

void ExtensionManager::loadContainerConfig()
{
//    kdDebug(1210) << "ExtensionManager::loadContainerConfig()" << endl;

    KConfig* config = KGlobal::config();

    // read extension list
    config->setGroup("General");
    QStringList elist = config->readListEntry("Extensions2");

    // now restore the extensions
    for( QStringList::Iterator it = elist.begin();
         it != elist.end(); ++it )
    {
        // extension id
        QString extensionId(*it);

        // create a matching applet container
        if(!extensionId.contains("Extension") > 0)
            continue;

        // is there a config group for this extension?
        if(!config->hasGroup(extensionId))
            continue;

        // set config group
        config->setGroup(extensionId);

        ExtensionContainer* e = PluginManager::pluginManager()->createExtensionContainer(
            config->readPathEntry("DesktopFile"),
            true, // is startup
            config->readPathEntry("ConfigFile") );

        if(e)
            addContainer(e);
    }
}

void ExtensionManager::addExtension( const QString& desktopFile )
{
    ExtensionContainer *e = PluginManager::pluginManager()->createExtensionContainer(
        desktopFile,
        false,            // is startup
        QString::null  ); // no config

    kdDebug(1210) << "ExtensionManager::addExtension" << endl;

    if(e) {
        e->readConfig();
	kdDebug(1210)<<"after e->readConfig(): pos="<<e->position()<<endl;
        addContainer(e);
        e->show();
        saveContainerConfig();
    }
}

void ExtensionManager::addContainer(ExtensionContainer* e)
{
    if (!e)
	return;

    setUniqueId(e);
    _containers.append(e);

    connect( e, SIGNAL( removeme(ExtensionContainer*) ),
	     SLOT( removeContainer(ExtensionContainer*) ) );

    if (e->inherits("ExternalExtensionContainer"))
	connect(e, SIGNAL(embeddedWindowDestroyed() ), this,
		SLOT( embeddedWindowDestroyed()));
}

void ExtensionManager::removeContainer(ExtensionContainer* e)
{
    if (!e)
	return;

    e->removeSessionConfigFile();
    _containers.removeRef(e);
    e->deleteLater(); // Wait till we return to the main event loop
    saveContainerConfig(true);
}

void ExtensionManager::removeAllContainers()
{
    while (!_containers.isEmpty()) {
	ExtensionContainer* e = _containers.first();
	_containers.removeRef(e);
	delete e;
    }
}

void ExtensionManager::setUniqueId(ExtensionContainer* e)
{
    QString idBase = "Extension_%1";
    QString newId;
    int i = 0;
    bool unique = false;

    while(!unique) {
	i++;
	newId = idBase.arg(i);

	unique = true;
	for( QPtrListIterator<ExtensionContainer> it(_containers); it.current() ; ++it ) {
	    ExtensionContainer* b = it.current();
	    if (b->extensionId() == newId) {
		unique = false;
		break;
	    }
	}
    }
    e->setExtensionId(newId);
}

void ExtensionManager::embeddedWindowDestroyed()
{
    if (sender() && sender()->inherits("ExternalExtensionContainer"))
	removeContainer((ExternalExtensionContainer*)sender());
}
