/***************************************************************************
 *   Copyright (C) 2003 by liuspider                                       *
 *   liuspider@users.sourceforge.net                                       *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/
#define USE_SCIM_KDE_SETTINGS
#include "skimpluginmanager.h"

#include "config.h"

#if HAVE_UNISTD_H
#include <unistd.h>
#else
//oops, it seems you do not have the unistd.h header file, then where is the "daemon" function 
//declared? If you have such a "special" system, please inform me.
#endif

#include <kapplication.h> 
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kglobal.h>
#include <config.h>
// #include <dcopclient.h>  
#include <kplugininfo.h>

static const char description[] =
    I18N_NOOP("KDE Frontend for SCIM Input Method Platform");

static KCmdLineOptions options[] =
{
    { "d", I18N_NOOP( "Start as daemon." ), 0 },
    { "l", I18N_NOOP( "List all availabe skim plugins." ), 0 },
    { "c <name>", I18N_NOOP( "Uses specified Config module." ), 0 },
    { "p <enabled plugins>", I18N_NOOP( "A comma separated list of plugin names. All of these plugins will be loaded no matter whether they are enabled in the setting file." ), 0 },
    { "np <disabled plugins>", I18N_NOOP( "A comma separated list of plugin names. All of these plugins will be disabled no matter whether they are disabled in the setting file." ), 0 },
    { "no-stay", I18N_NOOP( "Quit if no connected client." ), "false" },
    { "v", I18N_NOOP( "Enable debug info, multiple -v for more." ), "false" },
    { "V", I18N_NOOP( "Current version of skim" ), 0 },
    { "o <file>", I18N_NOOP( "Output debug file.(No effort, always use none)" ), 0 },
    { "f", I18N_NOOP( "Force start even if scim panel socket can not be established." ), 0 },
    KCmdLineLastOption
};

void make_daemon ()
{
    if (daemon (1, 1) == -1)
        std::cerr << "Error to make myself into a daemon!\n";

    return;
}

int main( int argc, char ** argv )
{
    KAboutData about(PACKAGE, "SKIM",
        VERSION " (compiled with scim-lib " SCIM_VERSION ")",
        description, KAboutData::License_GPL_V2, "(C) 2004 LiuCougar",
        "SCIM Mail List <scim@freedesktop.org>",
        "http://scim.freedesktop.org/Software/ScimKDE",
        "liuspider@users.sourceforge.net");
    about.addAuthor( "LiuCougar (liuspider)", I18N_NOOP("Core Developer"),
      "liuspider@users.sourceforge.net" );
    about.addCredit ( "JamesSu", I18N_NOOP("SCIM Core Author"), "suzhe@tsinghua.org.cn" );
    about.addAuthor ( "JanHefti", I18N_NOOP("Doc writer and German translator"),
      "j.hefti@hamburg.de" );
    about.addAuthor ( "KitaeKim", I18N_NOOP("Art designer and Korean translator"),
      "neeum@yahoo.com" );
    about.addAuthor ( "YukikoBando", I18N_NOOP("Japanese translator"),
      "ybando@k6.dion.ne.jp" );
    about.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\\nYour names")
        ,I18N_NOOP("_: EMAIL OF TRANSLATORS\\nYour emails"));

    QString curarg;
    scim::uint32 verbose_level = 0;

    QStringList otherArgs;

    for(int i = 1; i < argc ; i++)
    {
        curarg = argv[i];
        if( curarg == "-v" )
            verbose_level++;
        else if( curarg == "--no-stay")
            otherArgs.push_back("no-stay");
        else if (curarg == "-c" ) {
            otherArgs.push_back("c");
            otherArgs.push_back(argv[++i]);
        } else if( curarg == "-f")
            otherArgs.push_back("force");
    }
    
    //noxim is necessary to disable xim support in qt for this app
    const char* fake_arg1 =  "--noxim";
    char* fake_argv[10] = {argv[0], const_cast<char *>(fake_arg1), 0, 0, 0, 0, 0};
    for(int i = 1; i < argc; i++)
    {
      curarg = argv[i];
      if(curarg != "-V" && curarg != "-v")
        fake_argv[i+1] = argv[i];
      else {
        if(curarg == "-V" ) {
          fake_argv[1] = const_cast<char *>("-v");
          break;
        }
      }
    }
    KCmdLineArgs::init(argc+1, fake_argv, &about);

    KCmdLineArgs::addCmdLineOptions( options );

    scim::DebugOutput::set_verbose_level( verbose_level );
    scim::DebugOutput::disable_debug (SCIM_DEBUG_AllMask);
    scim::DebugOutput::enable_debug (/*SCIM_DEBUG_FrontEndMask |*/ SCIM_DEBUG_MainMask);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    
    if( args->isSet("l") ) {
      new KInstance(PACKAGE);
      QValueList<KPluginInfo *> info = SkimPluginManager::allAvailablePlugins();
      std::cout << i18n("Installed skim Plugins:\n\tName\t\t\tComment\n");
      for(uint i = 0; i < info.size(); i++) {
        std::cout << "\t" << info[i]->pluginName() << "\t" << info[i]->comment() << "\n"; 
      }
      return 0;
    }
    
    QCString p = args->getOption("p"), np = args->getOption("np");
    QStringList enabledPlugins, disabledPlugins;
    if( p.length() )
      enabledPlugins = QStringList::split(",", p);

    if( np.length() )
      disabledPlugins = QStringList::split(",", np);
    
    if( args->isSet("d") )
        make_daemon ();

    KApplication * kAppMainThread = new KApplication();
    if( kAppMainThread->isRestored() && !ScimKdeSettings::autoStart() )
      return 127; //when skim should not auto start, restore from session is not permitted

    SkimPluginManager* allModules = new SkimPluginManager(enabledPlugins, disabledPlugins, otherArgs);
    allModules->loadAllPlugins();
//     kapp->connect(kapp, SIGNAL(lastWindowClosed()), kapp, SLOT(quit()));
    return kAppMainThread->exec();
}
