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

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);
    }
}

Position ExtensionManager::initialPosition(Position prefered)
{
    // Guess a good position
    bool positions[::Bottom+1];
    for(int i = 0; i <= (int) ::Bottom; i++)
       positions[i] = true;
       
    positions[(int) Panel::the()->position()] = false;

    for(ExtensionContainer *c = _containers.first(); c; c = _containers.next())
    {
       positions[(int) c->position()] = false;
    }
    Position pos = prefered;
    if (positions[(int)pos])
       return pos;
       
    pos = (Position) (pos ^ 1);
    if (positions[(int)pos])
       return pos;

    pos = (Position) (pos ^ 3);
    if (positions[(int)pos])
       return pos;

    pos = (Position) (pos ^ 1);
    if (positions[(int)pos])
       return pos;
    
    return prefered;
}

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

    if(e) {
        e->readConfig();
        addContainer(e);
        e->show();
        saveContainerConfig();
    }
}

void ExtensionManager::addContainer(ExtensionContainer* e)
{
    assert( e );

    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 *a)
{
    if (a) {
	a->removeSessionConfigFile();
	_containers.removeRef(a);
	a->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());
}
