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

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 <kapp.h>
#include <kglobal.h>
#include <kstddirs.h>
#include <kdebug.h>
#include <kwinmodule.h>
#include <kwin.h>
#include <kconfig.h>

#include "global.h"
#include "appletinfo.h"
#include "userrectsel.h"
#include "container_extension.h"
#include "extensionmanager.h"
#include "extensionmanager.moc"

ExtensionManager::ExtensionManager(QObject* parent, const char* name)
    : QObject(parent, name), _init (false)
{
    _containers.setAutoDelete(false);

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

    if(config->hasKey("Extensions2"))
	loadContainerConfig();
    else
	defaultContainerConfig();
    connect(PGlobal::kwin_module, SIGNAL(strutChanged()), this, SLOT(slotUpdateContainerLayout()));
}

ExtensionManager::~ExtensionManager()
{
    removeAllContainers();
}

void ExtensionManager::defaultContainerConfig()
{
    kdDebug(1210) << "ExtensionManager::defaultContainerConfig()" << endl;
    removeAllContainers();

    /*
    // external taskbar
    QString df = KGlobal::dirs()->findResource("extensions", "ktaskbarextension.desktop");
    InternalExtensionContainer *e1 = new InternalExtensionContainer(AppletInfo(df));
    e1->slotSetPosition(Bottom);
    addContainer(e1);
    */

    updateContainerLayout();
    saveContainerConfig();
}

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

    KConfig *config = KGlobal::config();
    config->setGroup("General");

    // build the extension list
    QStringList elist;

    QListIterator<ExtensionContainer> it(_containers);
    for(; it.current() ; ++it)
	elist.append( it.current()->extensionId() );

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

    // write extension config
    it.toFirst();
    for(; it.current() ; ++it)
	{
	    ExtensionContainer* a = it.current();

	    // write position
	    config->setGroup(a->extensionId());
	    config->writeEntry("Position", a->position());

	    // let the applet container write custom data fields
	    if(!layoutOnly)
		a->saveConfiguration(a->extensionId());
	}
    config->sync();
}

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

    KConfig *config = KGlobal::config();

    removeAllContainers();

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

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

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

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

	    ExtensionContainer* e = 0;

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

	    KConfig *config = KGlobal::config();
	    config->setGroup(group);

	    QString df = KGlobal::dirs()->findResource("extensions", config->readEntry("DesktopFile"));
	    AppletInfo info(df);

	    QString configFile = config->readEntry("ConfigFile");
	    if (!configFile.isNull()) info.setConfigFile(configFile);

	    int pos = config->readNumEntry("Position", 1);

	    config->setGroup("General");

	    // child panels can be internal only
	    bool ischildpanel = (df.contains("childpanelextension") > 0);

	    if(config->readNumEntry("SecurityLevel", 1) == 0 && !ischildpanel)
		{
		    QString lib = info.library().mid(3, info.library().length());
		    bool trustedextension = false;
		    for ( QStringList::Iterator it = trusted.begin(); it != trusted.end(); ++it )
			{
			    if ((*it) == lib)
				trustedextension = true;
			}

		    if (trustedextension == true)
			e = new InternalExtensionContainer(info);
		    else
			e = new ExternalExtensionContainer(info);
		}
	    else
		e = new InternalExtensionContainer(info);

	    if (e) {
		e->slotSetPosition((Position)pos);
		addContainer(e, true);
	    }
	    it++;
	}

    updateContainerLayout();
}

void ExtensionManager::addExtension(const QString &desktopFile, bool internal)
{
    QString df = KGlobal::dirs()->findResource("extensions", desktopFile);
    AppletInfo info(df);

    ExtensionContainer *e;

    // child panels can be internal only
    if (desktopFile.contains("childpanelextension") > 0) internal = true;

    if (internal) {
	e = new InternalExtensionContainer(info);
	addContainer(e);
	updateContainerLayout();
	saveContainerConfig();
    }
    else {
	e = new ExternalExtensionContainer(info);
	connect(e, SIGNAL(docked(ExternalExtensionContainer*)),
		    SLOT(slotAddExternal(ExternalExtensionContainer*)));
    }
}

void ExtensionManager::slotAddExternal(ExternalExtensionContainer* e)
{
    addContainer(e);
    updateContainerLayout();
    saveContainerConfig();
}

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

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

    connect(e, SIGNAL(moveme(ExtensionContainer*) ),
	    SLOT( slotMoveContainer(ExtensionContainer*)));

    connect(e, SIGNAL(removeme(ExtensionContainer*) ),
	    SLOT( slotRemoveContainer(ExtensionContainer*)));
    connect(e, SIGNAL(requestSave()),
	    SLOT(slotSaveContainerConfig()));
    connect(e, SIGNAL(updateLayout() ), this,
	    SLOT( slotUpdateContainerLayout()));

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

    if (hidden)
	e->hide();
    else
	e->show();
    e->configure();
}

void ExtensionManager::removeContainer(ExtensionContainer *a)
{
    if (a) {
	a->removeSessionConfigFile();
	delete a;
	_containers.removeRef(a);
    }

    updateContainerLayout();
    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;
	    QListIterator<ExtensionContainer> it(_containers);
	    for(; it.current() ; ++it)
		{
		    ExtensionContainer* b = static_cast<ExtensionContainer*>(it.current());
		    if (b->extensionId() == newId)
			{
			    unique = false;
			    break;
			}
		}
	}
    e->setExtensionId(newId);
}

void ExtensionManager::updateContainerLayout()
{
    if (!_init) return;

    QRect a = effectiveWorkArea();
    QRect r(QApplication::desktop()->geometry());

    if (a.bottom() != r.bottom())
	a.setBottom(a.bottom()-1);

    if (a.right() != r.right())
	a.setRight(a.right()-1);

    for (ExtensionContainer* e = _containers.first(); e != 0; e = _containers.next())
	{
	    if (!e->isVisible())
		e->show();

	    if(e->position() == Top){

		QSize s(a.width(), 100);
		s = e->sizeHint(Top, s);
		e->setGeometry(a.left(), a.top(), s.width(), s.height());

		// only call KWin::setStrut when the strut is really changed
		NETStrut strut;
		strut.top = e->pos().y() + e->height();

		if (!PGlobal::areEqual(PGlobal::strutMap[e->winId()], strut)) {
		    PGlobal::strutMap.replace(e->winId(), strut);
		    KWin::setStrut(e->winId(), 0, 0,  e->pos().y() + e->height(), 0);
		}
		a.setTop(a.top() + s.height());
	    }
	    else if (e->position() == Bottom) {
		QSize s(a.width(), 100);
		s = e->sizeHint(Bottom, s);
		e->setGeometry(a.left(), a.bottom() + 1 - s.height(), s.width(), s.height());

		// only call KWin::setStrut when the strut is really changed
		NETStrut strut;
		strut.bottom = r.bottom() - e->pos().y();

		if (!PGlobal::areEqual(PGlobal::strutMap[e->winId()], strut)) {
		    PGlobal::strutMap.replace(e->winId(), strut);
		    KWin::setStrut(e->winId(), 0, 0, 0,  r.bottom() - e->pos().y());
		}
		a.setBottom(a.bottom() - s.height());
	    }
	    else if (e->position() == Left) {
		QSize s(100, a.height());
		s = e->sizeHint(Left, s);
		e->setGeometry(a.left(), a.top(), s.width(), s.height());

		// only call KWin::setStrut when the strut is really changed
		NETStrut strut;
		strut.left = e->pos().x() + e->width();

		if (!PGlobal::areEqual(PGlobal::strutMap[e->winId()], strut)) {
		    PGlobal::strutMap.replace(e->winId(), strut);
		    KWin::setStrut(e->winId(), e->pos().x() + e->width(), 0, 0, 0);
		}
		a.setLeft(a.left() + s.width());
	    }
	    else if (e->position() == Right) {
		QSize s(100, a.height());
		s = e->sizeHint(Right, s);
		e->setGeometry(a.right() + 1 - s.width(), a.top(), s.width(), s.height());

		// only call KWin::setStrut when the strut is really changed
		NETStrut strut;
		strut.right = r.right() - e->pos().x();

		if (!PGlobal::areEqual(PGlobal::strutMap[e->winId()], strut)) {
		    PGlobal::strutMap.replace(e->winId(), strut);
		    KWin::setStrut(e->winId(), 0, r.right() - e->pos().x(), 0, 0);
		}
		a.setRight(a.right() - s.width());
	    }
	}
}

void ExtensionManager::slotUpdateContainerLayout()
{
    _init = true;
    updateContainerLayout();
}

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

void ExtensionManager::slotSaveContainerConfig()
{
    saveContainerConfig();
}

void ExtensionManager::slotRemoveContainer(ExtensionContainer* c)
{
    removeContainer(c);
}

void ExtensionManager::slotMoveContainer(ExtensionContainer* c)
{
    if(!c) return;

    QApplication::syncX();
    QValueList<QRect> rects;

    QValueList<WId> list;
    list.append(c->winId());
    QRect a = PGlobal::kwin_module->workArea(list);

    QSize stop = c->sizeHint(Top, QSize(a.width(), 100));
    QSize sbottom = c->sizeHint(Bottom, QSize(a.width(), 100));
    QSize sleft = c->sizeHint(Left, QSize(100, a.height()));
    QSize sright = c->sizeHint(Right, QSize(100, a.height()));

    rects.append( QRect(  a.left(), a.top(), sleft.width(), sleft.height() ) );
    rects.append( QRect(  a.right() - sright.width() + 1, a.top(), sright.width(), sright.height() ) );
    rects.append( QRect(  a.left(), a.top(), stop.width(), stop.height() ) );
    rects.append( QRect(  a.left(), a.bottom() - sbottom.height() + 1, sbottom.width(), sbottom.height() ) );
    Position newpos = (Position) UserRectSel::select(rects, c->position());

    c->slotSetPosition(newpos);
    updateContainerLayout();
    saveContainerConfig(true);
}

void ExtensionManager::configure()
{
    for (QListIterator<ExtensionContainer> it(_containers); it.current(); ++it )
	{
	    ExtensionContainer *a = it.current();
	    if (a)
		a->configure();
	}
}

QRect ExtensionManager::effectiveWorkArea()
{
    QValueList<WId> list;
    for (ExtensionContainer* e = _containers.first(); e != 0; e = _containers.next()) {
	if (e->isVisible())
	    list.append(e->winId());
    }

    return (PGlobal::kwin_module->workArea(list));
}

bool ExtensionManager::hasInstance(AppletInfo* info) const
{
    bool found = false;

    for (QListIterator<ExtensionContainer> it(_containers); it.current(); ++it ) {
        ExtensionContainer *a = static_cast<ExtensionContainer*>(it.current());
        if (a->info().library() == info->library()) {
            found = true;
            break;
        }
    }
    return found;
}
