/* ****************************************************************************
  This file is part of KBabel

  Copyright (C) 1999-2001 by Matthias Kiefer
                            <matthias.kiefer@gmx.de>
		2002-2003  by Stanislav Visnovsky
			    <visnovsky@kde.org>

  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.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

**************************************************************************** */
#include "kbabel.h"
#include "kbabeliface.h"
#include "catalog.h"
#include "kbabelsplash.h"
#include "findoptions.h"

#include "version.h"

#include <dcopclient.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kcursor.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kuniqueapplication.h>
#include <kwin.h>

#include <qfile.h>
#include <qfileinfo.h>
#include <qtimer.h>

class KBabelInterface : public KBabelIface
{
public:
    KBabelInterface();

    virtual void openURL(QCString url, QCString package, WId window, int newWindow);
    virtual void openURL(QCString url, QCString package, WId window, int newWindow, QCString projectFile);
    virtual void openTemplate(QCString openFilename, QCString saveFilename, QCString package, int newWindow );
    virtual void openTemplate(QCString openFilename, QCString saveFilename, QCString package, int newWindow, QCString projectFile );
    virtual void gotoFileEntry(QCString url, QCString msgid);
    virtual void gotoFileEntry(QCString url, QCString msgid, QCString projectFile);
    virtual bool findInFile(QCString fileSource, QCString url, 
	QString findStr, int caseSensitive, int wholeWords, int isRegExp,
	int inMsgid, int inMsgstr, int inComment,
	int ignoreAccelMarker, int ignoreContextInfo, int askForNextFile, int askForSave);
    virtual bool replaceInFile(QCString fileSource, QCString url, 
	QString findStr, QString replaceStr, int caseSensitive, int wholeWords, int isRegExp,
	int inMsgid, int inMsgstr, int inComment,
	int ignoreAccelMarker, int ignoreContextInfo, int ask, int askForNextFile, int askForSave);
    virtual void spellcheck(QStringList fileList);
private:
    KBabel* findInstance( QCString file, QCString project );
};


class KBabelApp : public KUniqueApplication
{
public:
    KBabelApp();
    virtual ~KBabelApp();

    virtual int newInstance();

private:
    KBabelInterface *kbInterface;
};

KBabelApp::KBabelApp()
    : KUniqueApplication()
{
    kbInterface = new KBabelInterface;
}

KBabelApp::~KBabelApp()
{
    delete kbInterface;
}

int KBabelApp::newInstance()
{
    bool first=true;
    if(KBabel::memberList && !KBabel::memberList->isEmpty())
    {
        first=false;
    }
        
    // see if we are starting with session management => isRestored and first
    if (!isRestored() || !first)
    {
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
        
        QTimer timer;
        QWidget *splash=0;
        bool showSplash=args->isSet("splash");

        if( showSplash && first )
        {
            setOverrideCursor(KCursor::waitCursor());
            splash = new KBabelSplash();
	    splash->show();
            timer.start(4000,true);
        }

        QString projectFile=args->getOption("project");
	if( !projectFile.isEmpty() )
	{
	    QFileInfo fi(projectFile);
	    projectFile = fi.absFilePath();
	}
	
	QCString msgid=args->getOption("gotomsgid");
        if(!msgid.isEmpty() && args->count() > 0)
        {
            kdDebug(KBABEL) << "gotomsgid" << endl;
            QString m = QString::fromLocal8Bit(msgid);
            kbInterface->gotoFileEntry(args->url(0).url().utf8(),m.utf8());
        }
        else
        {
            // no session.. just start up normally
    	    KBabel *widget=0;
            if(args->count() > 0)
            {
                KURL u = args->url(0);
                widget=KBabel::winForURL(u,projectFile);
            }

            if(!widget)
                widget=KBabel::emptyWin(projectFile);

            if(!widget)
                widget=new KBabel(projectFile);
        
	    kapp->dcopClient()->suspend();
	    
            while(timer.isActive()) // let the user admire the splash screen ;-)
                processEvents();
        
            widget->show();
            for (int i=0; i < args->count(); i++)
            {
               widget->open( args->url(i) , QString::null, i != 0 );
            }
	    kapp->dcopClient()->resume();
        }


        args->clear();

        if(KBabelSplash::instance)
        {
            delete KBabelSplash::instance;
        }
        if(showSplash)
        {
            KApplication::restoreOverrideCursor();
            /*
            KMessageBox::information(0,
                    "This is a development version of KBabel!\n"
                    "Please double check the files you edit "
                    "and save with this version for correctness.\n"
                    "Please report any bug you find to kiefer@kde.org.\n"
                    "Thanks.", "Warning");
            */
        }
    }

    return 0;
}

KBabelInterface::KBabelInterface()
    : DCOPObject("KBabelIFace")
{
}

void KBabelInterface::openURL(QCString url, QCString package, WId window, int newWindow)
{
    openURL(url,package,window,newWindow, QCString());
}

void KBabelInterface::openURL(QCString url, QCString package, WId window, int newWindow, QCString projectFile)
{
    QString project(projectFile);
    
    KURL u(QString::fromLocal8Bit(url));
    KBabel *kb = KBabel::winForURL(u,project);
    if(kb)
    {
        KWin::setActiveWindow(kb->topLevelWidget()->winId());
    }
    else
    {
        KMainWindow *mw = 0;
        if(KMainWindow::memberList && !KMainWindow::memberList->isEmpty())
            mw=KMainWindow::memberList->first();

        while( mw ) {
	    if( mw->inherits("KBabel") && mw->winId() == window)
    	    {
        	kb = static_cast<KBabel*>(mw);
        	KWin::setActiveWindow(kb->topLevelWidget()->winId());
        	kb->open(u, QString::fromUtf8(package),newWindow);
		return ;
	    }
	    mw = KMainWindow::memberList->next();
        }

        if(KMainWindow::memberList && !KMainWindow::memberList->isEmpty())
            mw=KMainWindow::memberList->first();

        while( mw ) {
	    if( mw->inherits("KBabel") && static_cast<KBabel*>(mw)->project()==project)
    	    {
        	kb = static_cast<KBabel*>(mw);
        	KWin::setActiveWindow(kb->topLevelWidget()->winId());
        	kb->open(u, QString::fromUtf8(package),newWindow);
		return ;
	    }
	    mw = KMainWindow::memberList->next();
        }

        if( !mw ) 
	{
	    kb = new KBabel(project);
    	    kb->show();
	} else kb = static_cast<KBabel*>(mw);
        KWin::setActiveWindow(kb->topLevelWidget()->winId());
	kb->raise();
        kb->open(u,QString::fromUtf8(package),newWindow);
    }
}

void KBabelInterface::openTemplate(QCString openFilename, QCString saveFilename, QCString package, int newWindow)
{
    openTemplate(openFilename, saveFilename, package, newWindow, QCString());
}

void KBabelInterface::openTemplate(QCString openFilename, QCString saveFilename, QCString package, int newWindow, QCString projectFile)
{
    QString project(projectFile);
    
    KURL u(saveFilename.data());
    KURL t(openFilename.data());
    KBabel *kb = KBabel::winForURL(u, project);
    if(kb)
    {
        KWin::setActiveWindow(kb->topLevelWidget()->winId());
    }
    else
    {
        KMainWindow *mw = 0;
        if(KMainWindow::memberList && !KMainWindow::memberList->isEmpty())
            mw=KMainWindow::memberList->first();

        if(mw && mw->inherits("KBabel") && static_cast<KBabel*>(mw)->project()==project)
        {
            kb = static_cast<KBabel*>(mw);
            KWin::setActiveWindow(kb->topLevelWidget()->winId());
	    kb->raise();
            kb->openTemplate(t,u,QString::fromUtf8(package),newWindow);
        }
        else
        {
            kb = new KBabel(project);
            kb->show();
            KWin::setActiveWindow(kb->topLevelWidget()->winId());
	    kb->raise();
            kb->openTemplate(t,u,QString::fromUtf8(package));
        }
    }
}

void KBabelInterface::gotoFileEntry(QCString url, QCString m)
{    
    gotoFileEntry(url,m,QCString());
}

void KBabelInterface::gotoFileEntry(QCString url, QCString m, QCString projectFile)
{    
    QString project(projectFile);
    QString msgid = QString::fromUtf8(m);
    KBabel *kb = findInstance( url, projectFile );

    if(!kb) return;
    
    int index = kb->m_view->catalog()->indexForMsgid(msgid);
    if(index >= 0)
    {
        kb->m_view->gotoEntry((uint)index);
    }
}

bool KBabelInterface::findInFile(QCString fileSource, QCString url, 
	QString findStr, int caseSensitive, int wholeWords, int isRegExp,
	int inMsgid, int inMsgstr, int inComment,
	int ignoreAccelMarker, int ignoreContextInfo, int askForNextFile, int askForSave)
{    
    kdDebug() << "findInFile (" <<fileSource<< "): " << url << " for " << findStr << endl;
    
    KBabel *kb = findInstance(url, QCString());

    if(!kb) return false;
    
    FindOptions options;
    options.findStr = findStr;
    options.caseSensitive = (caseSensitive>0);
    options.fromCursor = false;
    options.backwards = false;
    options.wholeWords = (wholeWords>0);
    options.isRegExp = (isRegExp>0);
    options.inMsgid = (inMsgid>0);
    options.inMsgstr = (inMsgstr>0);
    options.inComment = (inComment>0);
    options.ignoreAccelMarker = (ignoreAccelMarker>0);
    options.ignoreContextInfo = (ignoreContextInfo>0);
    options.askForNextFile = (askForNextFile>0);
    options.askForSave = (askForSave>0);
    kb->m_view->findInFile(fileSource, options);
    
    return true;
}

bool KBabelInterface::replaceInFile(QCString fileSource, QCString url, 
	QString findStr, QString replaceStr, int caseSensitive, int wholeWords, int isRegExp,
	int inMsgid, int inMsgstr, int inComment,
	int ignoreAccelMarker, int ignoreContextInfo, int ask, int askForNextFile, int askForSave)
{    
    kdDebug() << "replaceInFile (" <<fileSource<< "): " << url << " for " << findStr << endl;

    KBabel *kb = findInstance( fileSource, QCString() );
    
    if( !kb ) return false;

    ReplaceOptions options;
    options.findStr = findStr;
    options.replaceStr = replaceStr;
    options.caseSensitive = (caseSensitive>0);
    options.fromCursor = false;
    options.backwards = false;
    options.wholeWords = (wholeWords>0);
    options.isRegExp = (isRegExp>0);
    options.inMsgid = (inMsgid>0);
    options.inMsgstr = (inMsgstr>0);
    options.inComment = (inComment>0);
    options.ignoreAccelMarker = (ignoreAccelMarker>0);
    options.ignoreContextInfo = (ignoreContextInfo>0);
    options.ask = (ask>0);
    options.askForNextFile = (askForNextFile>0);
    options.askForSave = (askForSave>0);
    kb->m_view->replaceInFile(fileSource, options);
    
    return true;
}

void KBabelInterface::spellcheck(QStringList fileList)
{
    QCString nullString;
    KBabel *kb = findInstance(nullString, nullString);
    kb->show();
    kb->spellcheckMoreFiles( fileList );
}

KBabel* KBabelInterface::findInstance( QCString url, QCString project)
{
    KURL u = url;
    KBabel *kb = 0;
    if( !url.isNull() )
    {
	kb = KBabel::winForURL(u,project);

	if(kb)
	{
    	    KWin::setActiveWindow(kb->topLevelWidget()->winId());
	}
    }
    
    if( !kb )
    {
	kb = KBabel::emptyWin(project);
	if( !kb ) kb = new KBabel(project);
        kb->show();
        if( !url.isEmpty() ) kb->open(u);
    } 
    return kb;
}

static KCmdLineOptions options[] =
{
   {"gotomsgid <msgid>",I18N_NOOP("Go to entry with msgid <msgid>"),0},
   {"nosplash",I18N_NOOP("disable splashscreen at startup"),0},
   {"project <configfile>",I18N_NOOP("File to load configuration from"),0},
   {"+[file]",I18N_NOOP("files to open"),0},
   {0,0,0}
};


int main(int argc, char **argv)
{
    KAboutData about("kbabel",I18N_NOOP("KBabel"),VERSION,
       I18N_NOOP("An advanced PO file editor"),KAboutData::License_GPL,
       I18N_NOOP("(c) 1999,2000,2001,2002 The KBabel developers"),0,"http://i18n.kde.org/tools/kbabel");

    about.addAuthor("Matthias Kiefer",I18N_NOOP("Original author"),"kiefer@kde.org");
    about.addAuthor("Wolfram Diestel"
         ,I18N_NOOP("Wrote diff algorithm, fixed KSpell and gave a lot "
         "of useful hints."),"wolfram@steloj.de");
    about.addAuthor("Andrea Rizzi",I18N_NOOP("Wrote the dictionary plugin "
		"for searching in a database and some other code.")
            ,"rizzi@kde.org");
    about.addAuthor("Stanislav Visnovsky",I18N_NOOP("Current maintainer, porting to KDE3/Qt3.")
	,"visnovsky@kde.org");
    about.addAuthor("Marco Wegner",I18N_NOOP("Bug fixes and KFilePlugin for PO files.") 
         ,"dubbleu@web.de");

    about.addCredit("Claudiu Costin",I18N_NOOP("Wrote documentation and sent "
		"many bug reports and suggestions for improvements.")
         ,"claudiuc@geocities.com");
    about.addCredit("Thomas Diehl",I18N_NOOP("Gave many suggestions for the GUI "
         "and the behavior of KBabel. He also contributed the beautiful splash screen.")
            ,"thd@kde.org");
    about.addCredit("Stephan Kulow",I18N_NOOP("Helped keep KBabel up to date "
		"with the KDE API and gave a lot of other help."),"coolo@kde.org");
    about.addCredit("Stefan Asserhall",I18N_NOOP("Implemented XML validation/highlighting "
	 "plus other small fixes.") ,"stefan.asserhall@telia.com");
	about.addCredit("SuSE GmbH"
					,I18N_NOOP("Sponsored development of KBabel for a while.")
					,"suse@suse.de","http://www.suse.de");
    about.addCredit("",
            I18N_NOOP("KBabel contains code from the following projects:\n"
            "Qt by Trolltech and GNU gettext"));

    about.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names")
            ,I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

    // Initialize command line args
    KCmdLineArgs::init(argc, argv, &about);

    // Tell which options are supported
    KCmdLineArgs::addCmdLineOptions( options );

    // Add options from other components
    KUniqueApplication::addCmdLineOptions();


    if(!KUniqueApplication::start())
    {
        return 0;
    }
    
    KBabelApp app;
    
    if( app.isRestored() )
    {
	RESTORE(KBabel)
    }

    return app.exec();
}
