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

Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.

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 <qfileinfo.h>
#include <qpopupmenu.h>

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

#include "container_applet.h"
#include "container_extension.h"
#include "appletinfo.h"
#include "pluginloader.h"

#include "pluginmanager.h"
#include "pluginmanager.moc"

PluginManager* PluginManager::pluginManager()
{
    static PluginManager pluginManager;
    return &pluginManager;
}

PluginManager::PluginManager()
    : loadingPolicy( Startup )
{
}

QValueList<AppletInfo> PluginManager::applets() const
{
    return plugins( KGlobal::dirs()->findAllResources("applets", "*.desktop", false, true) );
}

QValueList<AppletInfo> PluginManager::extensions() const
{
    return plugins( KGlobal::dirs()->findAllResources("extensions", "*.desktop", false, true) );
}

QValueList<AppletInfo> PluginManager::plugins( const QStringList& desktopFiles ) const
{
    QValueList<AppletInfo> plugins;

    for ( QStringList::ConstIterator it = desktopFiles.begin();
          it != desktopFiles.end(); ++it ) {
        AppletInfo info( *it );
        plugins.append( info );
    }

    qHeapSort( plugins.begin(), plugins.end() );

    return plugins;
}

void PluginManager::configure()
{
    KConfig *config = KGlobal::config();
    config->setGroup("General");
    loadingPolicy = static_cast<InternalLoadingPolicy>(
         config->readNumEntry("SecurityLevel", 1) );
    trustedApplets = config->readListEntry("TrustedApplets");
    trustedExtensions = config->readListEntry("TrustedExtensions2");
}

bool PluginManager::trustedPlugin( const AppletInfo& info, bool isStartup )
{
    configure();

    if( loadingPolicy == All || (loadingPolicy == Startup && isStartup) ) {
        return true;
    }

    // Child panel applets must be loaded internally, because they require
    // access to the the main panel.
    if( info.library().contains("childpanel_panelextension") > 0 ) {
        return true;
    }

    for ( QStringList::Iterator it = trustedApplets.begin();
          it != trustedApplets.end(); ++it ) {
        if ((*it) == QFileInfo( info.desktopFile() ).baseName() ) {
            return true;
        }
    }
    for ( QStringList::Iterator it = trustedExtensions.begin();
         it != trustedExtensions.end(); ++it ) {
        if ((*it) == QFileInfo( info.desktopFile() ).baseName() ) {
           return true;
       }
   }
   return false;
}

AppletContainer* PluginManager::createAppletContainer(
    const QString& desktopFile, bool isStartup, const QString& configFile, QPopupMenu* opMenu, QWidget* parent )
{
    QString desktopPath = KGlobal::dirs()->findResource( "applets", desktopFile );

    // support the old (KDE 2.2) nameing scheme
    if( desktopPath.isEmpty() )
        desktopPath = KGlobal::dirs()->findResource( "applets",
                                                     desktopFile.right(
                                                     desktopFile.length() - 1 ) );

    if ( desktopPath.isEmpty() )
        return 0;

    AppletInfo info( desktopPath, configFile );

    if( info.isUniqueApplet() && PluginLoader::pluginLoader()->hasInstance(info) )
        return 0;

    AppletContainer* container;
    if( trustedPlugin( info, isStartup ) ) {
        container = new InternalAppletContainer( info, opMenu, parent );
    } else {
        container = new ExternalAppletContainer( info, opMenu, parent );
    }

    if (!container->isValid())
    {
        delete container;
        return 0;
    }

    return container;
}

ExtensionContainer* PluginManager::createExtensionContainer(
    const QString& desktopFile, bool isStartup, const QString& configFile )
{
    QString desktopPath = KGlobal::dirs()->findResource( "extensions", desktopFile );

    if( desktopPath.isEmpty() )
        return 0;

    AppletInfo info( desktopPath, configFile );

    if( info.isUniqueApplet() && PluginLoader::pluginLoader()->hasInstance(info) )
        return 0;

    ExtensionContainer* container;
    if( trustedPlugin( info, isStartup ) ) {
        container = new InternalExtensionContainer(info);
    } else {
        container = new ExternalExtensionContainer(info);
    }

    return container;
}
