/***************************************************************************
 *   Copyright (C) 2003 by Thomas Hasart                                   *
 *   thasart@gmx.de                                                        *
 *   Copyright (C) 2001-2002 by Bernd Gehrmann                             *
 *   bernd@kdevelop.org                                                    *
 *   Copyright (C) 2002 by Jakob Simon-Gaarde                              *
 *   jakob@jsg.dk                                                          *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "trollprojectpart.h"

#include <qdir.h>
#include <qfileinfo.h>
#include <qwhatsthis.h>
#include <kdeversion.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <qmessagebox.h>
#include <kdevgenericfactory.h>
#include <kaction.h>
#include <kparts/part.h>
#include <kprocess.h>
#include <makeoptionswidget.h>


#include "domutil.h"
#include "kdevcore.h"
#include "kdevmainwindow.h"
#include "kdevmakefrontend.h"
#include "kdevappfrontend.h"
#include "kdevpartcontroller.h"
#include "opiepackagingstuff.h"
#include "opiepackageconfigdlg.h"
#include "trollprojectwidget.h"
#include "runoptionswidget.h"
#include "config.h"
#include "envvartools.h"


typedef KDevGenericFactory<TrollProjectPart> TrollProjectFactory;
static const KAboutData data("kdevtrollproject", I18N_NOOP("QMake Manager"), "1.0");
K_EXPORT_COMPONENT_FACTORY( libkdevtrollproject, TrollProjectFactory( &data ) )

TrollProjectPart::TrollProjectPart(QObject *parent, const char *name, const QStringList& args )
    : KDevProject("TrollProject", "trollproject", parent, name ? name : "TrollProjectPart")
{
    setInstance(TrollProjectFactory::instance());

    if ( args.count() == 1 && args[0] == "TMake" )
        m_tmakeProject = true;
    else
        m_tmakeProject = false;

    setXMLFile("kdevtrollproject.rc");

    m_executeAfterBuild = false;

    m_opie = new OpiePackagingStuff( this );

    m_widget = new TrollProjectWidget(this);
    m_widget->setIcon(SmallIcon("make"));
    m_widget->setCaption(i18n("QMake Manager"));
    QWhatsThis::add(m_widget, i18n("<b>QMake manager</b><p>"
                                   "The QMake manager project tree consists of two parts. The 'overview' "
                                   "in the upper half shows the subprojects, each one having a "
                                   ".pro file. The 'details' view in the lower half shows the "
                                   "list of files for the active subproject selected in the overview."));

    mainWindow()->embedSelectViewRight(m_widget, i18n("QMake Manager"), i18n("QMake manager"));

    KAction *action;

    const QIconSet icon(SmallIcon("compfile"));
    action = new KAction( i18n("Compile &File"), "compfile", 0,
                          m_widget, SLOT(slotBuildFile()),
                          actionCollection(),"build_compilefile"  );
    action->setToolTip(i18n("Compile file"));
    action->setWhatsThis(i18n("<b>Compile file</b><p>Runs <b>make filename.o</b> command from the directory where 'filename' is the name of currently opened file.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));


    action = new KAction( i18n("&Build Project"), "make_kdevelop", Key_F8,
                          m_widget, SLOT(slotBuildProject()),
                          actionCollection(), "build_build_project" );
    action->setToolTip(i18n("Build project"));
    action->setWhatsThis(i18n("<b>Build project</b><p>Runs <b>make</b> from the project directory.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("&Rebuild Project"),"rebuild" , 0,
                          m_widget, SLOT(slotRebuildProject()),
                          actionCollection(),"build_rebuild_project"  );
    action->setToolTip(i18n("Rebuild project"));
    action->setWhatsThis(i18n("<b>Rebuild project</b><p>Runs <b>make clean</b> and then <b>make</b> from the project directory.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("&Clean Project"), 0,
                          m_widget, SLOT(slotCleanProject()),
                          actionCollection(), "build_clean_project" );
    action->setToolTip(i18n("Clean project"));
    action->setWhatsThis(i18n("<b>Clean project</b><p>Runs <b>make clean</b> command from the project directory.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("Execute Main Program"), "exec", SHIFT+Key_F9,
                          m_widget, SLOT(slotExecuteProject()),
                          actionCollection(), "build_execute_project" );
    action->setToolTip(i18n("Execute main program"));
    action->setWhatsThis(i18n("<b>Execute program</b><p>Executes the main program specified in project settings, <b>Run Options</b> tab."));





    action = new KAction( i18n("&Build Subproject"), "make_kdevelop", Key_F7,
                          m_widget, SLOT(slotBuildTarget()),
                          actionCollection(), "build_build_target" );
    action->setToolTip(i18n("Build subproject"));
    action->setWhatsThis(i18n("<b>Build subproject</b><p>Runs <b>make</b> from the current subproject directory. "
                              "Current subproject is a subproject selected in <b>QMake manager</b> 'overview' window.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("&Rebuild Subproject"), "rebuild", 0,
                          m_widget, SLOT(slotRebuildTarget()),
                          actionCollection(),"build_rebuild_target"  );
    action->setToolTip(i18n("Rebuild subproject"));
    action->setWhatsThis(i18n("<b>Rebuild subproject</b><p>Runs <b>make clean</b> and then <b>make</b> from the current subproject directory. "
                              "Current subproject is a subproject selected in <b>QMake manager</b> 'overview' window.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("&Clean Subproject"), 0,
                          m_widget, SLOT(slotCleanTarget()),
                          actionCollection(), "build_clean_target" );
    action->setToolTip(i18n("Clean subproject"));
    action->setWhatsThis(i18n("<b>Clean subproject</b><p>Runs <b>make clean</b> from the current subproject directory. "
                              "Current subproject is a subproject selected in <b>QMake manager</b> 'overview' window.<br>"
                              "Environment variables and make arguments can be specified "
                              "in the project settings dialog, <b>Make Options</b> tab."));

    action = new KAction( i18n("Execute Subproject"), "exec", 0,
                          m_widget, SLOT(slotExecuteTarget()),
                          actionCollection(), "build_execute_target" );
    action->setToolTip(i18n("Execute subproject"));
    action->setWhatsThis(i18n("<b>Execute subproject</b><p>Executes the target program for the currently selected subproject. "
        "This action is allowed only if a type of the subproject is 'application'. The type of the subproject can be "
        "defined in <b>Subproject Settings</b> dialog (open it from the subproject context menu)."));

    connect( core(), SIGNAL(projectConfigWidget(KDialogBase*)),
             this, SLOT(projectConfigWidget(KDialogBase*)) );

    connect( makeFrontend(), SIGNAL(commandFinished(const QString&)),
             this, SLOT(slotCommandFinished(const QString&)) );

/*
 * Opie stuff
 */
    KToggleAction *toc_action = new KToggleAction(  i18n("Build as QuickLaunch"), KShortcut(),
                                 this, SLOT(slotQuickLaunch(bool)),
                                 actionCollection(), "check_quick_app" );
    m_quickLaunch= DomUtil::readBoolEntry(*projectDom(), "/kdevtrollproject/opie/quick_app" );
    toc_action->setChecked(m_quickLaunch);
    connect(toc_action, SIGNAL(toggled(bool)),
            this, SLOT(slotQuickLaunch(bool)));

    action = new KAction(i18n("Build Package"), "", 0,
                         m_opie, SLOT(slotBuildPackage()),
                         actionCollection(), "build_package" );

    action = new KAction(i18n("Build Language Packages" ), "", 0,
                         m_opie, SLOT(slot18nPackage()),
                         actionCollection(), "build_i18n_packages");
    m_actMenu = new KActionMenu(i18n("Generate Translation files") , actionCollection(),
                             "generate_i18n_files" );
    m_opie->slotFillLanguage();

    action = new KAction(i18n("Update Languages"), "", 0,
                         m_opie, SLOT(slotUpdateAndRelease()),
                         actionCollection(), "update_and_release" );

    m_qmakeHeader = i18n("# File generated by kdevelop's qmake manager (opie version). \n"
                         "# ---------------------------------------------------------- \n"
                         "# Subdir relative project main directory: %s\n"
                         "# Target is %s %s\n");

    m_availableQtDirList = availableQtDirList();
    m_defaultQtDir = ::getenv( "QTDIR" );
    if( m_defaultQtDir.isEmpty() && !m_availableQtDirList.isEmpty() )
        m_defaultQtDir = m_availableQtDirList.front();
}


TrollProjectPart::~TrollProjectPart()
{
    if (m_widget)
        mainWindow()->removeView(m_widget);
    delete m_widget;
}

QString TrollProjectPart::makeEnvironment()
{
    // Get the make environment variables pairs into the environstr string
    // in the form of: "ENV_VARIABLE=ENV_VALUE"
    // Note that we quote the variable value due to the possibility of
    // embedded spaces
    DomUtil::PairList envvars =
        DomUtil::readPairListEntry(*projectDom(), "/kdevtrollproject/make/envvars", "envvar", "name", "value");

    QString environstr;
    DomUtil::PairList::ConstIterator it;
    bool hasQtDir = false;
    bool hasQMake = false;
    bool hasOpie  = false;
    for (it = envvars.begin(); it != envvars.end(); ++it) {
        if( (*it).first == "QTDIR" )
	    hasQtDir = true;
	else if( (*it).first == "QMAKESPEC" )
	    hasQMake = true;
        else if((*it).first == "OPIEDIR" )
            hasOpie = true;

        environstr += (*it).first;
        environstr += "=";
/*
#if (KDE_VERSION > 305)
        environstr += KProcess::quote((*it).second);
#else
        environstr += KShellProcess::quote((*it).second);
#endif
*/
        environstr += EnvVarTools::quote((*it).second);
        environstr += " ";
    }

    if( !hasQtDir )
    {
         environstr += QString( "QTDIR=" ) + EnvVarTools::quote( m_opieQt ) + QString( " " );
    }
    if (!hasOpie )
        environstr += QString( "OPIEDIR=" )+ EnvVarTools::quote( m_opieOpie ) + QString( " " );
    if( !hasQMake )
	environstr += QString("QMAKESPEC=") + EnvVarTools::quote( m_makeSpec ) + QString( " " );

    if ( m_quickLaunch )
        environstr += QString(" OPIE_BUILD_QUICK_APP=quick-app-lib " );

    return environstr;
}

void TrollProjectPart::projectConfigWidget(KDialogBase *dlg)
{
    QVBox *vbox;
    vbox = dlg->addVBoxPage(i18n("Run Options"));
    RunOptionsWidget *optdlg = new RunOptionsWidget(*projectDom(), "/kdevtrollproject", buildDirectory(), vbox);

    vbox = dlg->addVBoxPage(i18n("Make Options"));
    MakeOptionsWidget *w4 = new MakeOptionsWidget(*projectDom(), "/kdevtrollproject", vbox);

    vbox = dlg->addVBoxPage(i18n("Packaging Information"));
    OpiePackageConfigDlg *o_dlg = new OpiePackageConfigDlg(*projectDom(), "/kdevtrollproject", vbox );

    connect( dlg, SIGNAL(okClicked()), o_dlg, SLOT(slotAccept()));
    connect( dlg, SIGNAL(okClicked()), w4, SLOT(accept()) );
    connect( dlg, SIGNAL(okClicked()), optdlg, SLOT(accept()) );
}


void TrollProjectPart::openProject(const QString &dirName, const QString &projectName)
{
    m_widget->openProject(dirName);
    m_projectName = projectName;

    QDomDocument &dom = *projectDom();
    // Set the default directory radio to "executable"
    if (DomUtil::readEntry(dom, "/kdevtrollproject/run/directoryradio") == "" ) {
        DomUtil::writeEntry(dom, "/kdevtrollproject/run/directoryradio", "executable");
    }

    KDevProject::openProject( dirName, projectName );
}


void TrollProjectPart::closeProject()
{
    m_widget->closeProject();
}


QString TrollProjectPart::projectDirectory() const
{
  return m_widget->projectDirectory();
}


QString TrollProjectPart::buildDirectory() const
{
  return m_widget->projectDirectory();
}

QString TrollProjectPart::projectName() const
{
    return m_projectName;
}


/** Retuns a PairList with the run environment variables */
DomUtil::PairList TrollProjectPart::runEnvironmentVars() const
{
    return DomUtil::readPairListEntry(*projectDom(), "/kdevtrollproject/run/envvars", "envvar", "name", "value");
}


/** Retuns the currently selected run directory
  * The returned string can be:
  *   if run/directoryradio == executable
  *        The directory where the executable is
  *   if run/directoryradio == build
  *        The directory where the executable is relative to build directory
  *   if run/directoryradio == custom
  *        The custom directory absolute path
  */
QString TrollProjectPart::runDirectory() const
{
    QDomDocument &dom = *projectDom();

    QString directoryRadioString = DomUtil::readEntry(dom, "/kdevtrollproject/run/directoryradio");
    QString DomMainProgram = DomUtil::readEntry(dom, "/kdevtrollproject/run/mainprogram");

    if ( directoryRadioString == "build" )
        return buildDirectory();

    if ( directoryRadioString == "custom" )
        return DomUtil::readEntry(dom, "/kdevtrollproject/run/customdirectory");

    int pos = DomMainProgram.findRev('/');
    if (pos != -1)
        return buildDirectory() + "/" + DomMainProgram.left(pos);

    if ( DomMainProgram.isEmpty() )
    {
        return m_widget->subprojectDirectory();
    }
    return buildDirectory() + "/" + DomMainProgram;

}


/** Retuns the currently selected main program
  * The returned string can be:
  *   if run/directoryradio == executable
  *        The executable name
  *   if run/directoryradio == build
  *        The path to executable relative to build directory
  *   if run/directoryradio == custom or relative == false
  *        The absolute path to executable
  */
QString TrollProjectPart::mainProgram(bool relative) const
{
    QDomDocument &dom = *projectDom();

    QString directoryRadioString = DomUtil::readEntry(dom, "/kdevtrollproject/run/directoryradio");
    QString DomMainProgram = DomUtil::readEntry(dom, "/kdevtrollproject/run/mainprogram");

    if ( directoryRadioString == "custom" )
        return DomMainProgram;

    if ( relative == false && !DomMainProgram.isEmpty() )
        return buildDirectory() + "/" + DomMainProgram;

    if ( directoryRadioString == "executable" ) {
        int pos = DomMainProgram.findRev('/');
        if (pos != -1)
            return DomMainProgram.mid(pos+1);

        if ( DomMainProgram.isEmpty() )
        {
            return runDirectory() + "/" + m_widget->getCurrentOutputFilename();
        }
        return DomMainProgram;
    }
    else
        return DomMainProgram;
}


/** Retuns a QString with the run command line arguments */
QString TrollProjectPart::runArguments() const
{
    return DomUtil::readEntry(*projectDom(), "/kdevtrollproject/run/programargs");
}


QString TrollProjectPart::activeDirectory() const
{
    QDomDocument &dom = *projectDom();

    return DomUtil::readEntry(dom, "/kdevtrollproject/general/activedir");
}


QStringList TrollProjectPart::allFiles() const
{
    return m_widget->allFiles();
}


void TrollProjectPart::addFile(const QString &fileName)
{
	QStringList fileList;
	fileList.append ( fileName );

	this->addFiles ( fileList );
}

void TrollProjectPart::addFiles ( const QStringList &fileList )
{
    QStringList files = fileList;
    for (QStringList::iterator it = files.begin(); it != files.end(); ++it)
//        if (!(*it).contains(projectDirectory()))
        *it = projectDirectory() + "/" + (*it);

    m_widget->addFiles(files);

//	emit addedFilesToProject ( files );
}

void TrollProjectPart::removeFile(const QString & /* fileName */)
{
    /// \FIXME
/*	QStringList fileList;
	fileList.append ( fileName );

	this->removeFiles ( fileList );*/
}

void TrollProjectPart::removeFiles ( const QStringList& fileList )
{
/// \FIXME missing remove files functionality
// 	QStringList::ConstIterator it;
//
// 	it = fileList.begin();
//
// 	for ( ; it != fileList.end(); ++it )
// 	{
// 		FIXME
// 	}

	emit removedFilesFromProject ( fileList );
}
/*
void TrollProjectPart::startMakeCommand(const QString &dir, const QString &target)
{
    partController()->saveAllFiles();

    QFileInfo fi(dir + "/Makefile");
    if (!fi.exists()) {
        int r = KMessageBox::questionYesNo(m_widget, i18n("There is no Makefile in this directory. Run qmake first?"));
        if (r == KMessageBox::No)
            return;
        startQMakeCommand(dir);
    }
    QDomDocument &dom = *projectDom();

    if (target=="clean")
    {
      QString cmdline = DomUtil::readEntry(dom, "/kdevtrollproject/make/makebin");
      if (cmdline.isEmpty())
          cmdline = MAKE_COMMAND;
      cmdline += " clean";
      QString dircmd = "cd ";
      dircmd += dir;
      dircmd += " && ";
      cmdline.prepend(makeEnvironment());
      makeFrontend()->queueCommand(dir, dircmd + cmdline);
    }

    QString cmdline = DomUtil::readEntry(dom, "/kdevtrollproject/make/makebin");
    if (cmdline.isEmpty())
        cmdline = MAKE_COMMAND;
    if (!DomUtil::readBoolEntry(dom, "/kdevtrollproject/make/abortonerror"))
        cmdline += " -k";
    int jobs = DomUtil::readIntEntry(dom, "/kdevtrollproject/make/numberofjobs");
    if (jobs != 0) {
        cmdline += " -j";
        cmdline += QString::number(jobs);
    }
    if (DomUtil::readBoolEntry(dom, "/kdevtrollproject/make/dontact"))
        cmdline += " -n";

    cmdline += " ";
    cmdline += target;

    QString dircmd = "cd ";
    dircmd += dir;
    dircmd += " && ";

    cmdline.prepend(makeEnvironment());
    makeFrontend()->queueCommand(dir, dircmd + cmdline);
}
*/

void TrollProjectPart::startQMakeCommand(const QString &dir)
{
    QFileInfo fi(dir);

    QString cmdline = QString::fromLatin1( isTMakeProject() ? "tmake " : "qmake " );
//    cmdline += fi.baseName() + ".pro";
    QDir d(dir);
    QStringList l = d.entryList("*.pro");

    cmdline += l.count()?l[0]:(fi.baseName() + ".pro");

//    cmdline += QString::fromLatin1( " -o Makefile" );

    QString dircmd = "cd ";
    dircmd += dir;
    dircmd += " && ";

    cmdline.prepend(makeEnvironment());
    makeFrontend()->queueCommand(dir, dircmd + cmdline);
}

void TrollProjectPart::queueCmd(const QString &dir, const QString &cmd)
{
    makeFrontend()->queueCommand(dir, cmd);
}

void TrollProjectPart::slotCommandFinished( const QString& command )
{
    Q_UNUSED( command );

    if( m_buildCommand != command )
        return;

    m_buildCommand = QString::null;

    m_timestamp.clear();
    QStringList fileList = allFiles();
    QStringList::Iterator it = fileList.begin();
    while( it != fileList.end() ){
        QString fileName = *it;
        ++it;

        m_timestamp[ fileName ] = QFileInfo( projectDirectory(), fileName ).lastModified();
    }

    emit projectCompiled();

    if( m_executeAfterBuild ){
        m_widget->slotExecuteProject();
        m_executeAfterBuild = false;
    }
}

bool TrollProjectPart::isDirty()
{
    QStringList fileList = allFiles();
    QStringList::Iterator it = fileList.begin();
    while( it != fileList.end() ){
        QString fileName = *it;
        ++it;

        QMap<QString, QDateTime>::Iterator it = m_timestamp.find( fileName );
        QDateTime t = QFileInfo( projectDirectory(), fileName ).lastModified();
        if( it == m_timestamp.end() || *it != t ){
            return true;
        }
    }

    return false;
}

KDevProject::Options TrollProjectPart::options( )
{
    return UsesQMakeBuildSystem;
}

bool TrollProjectPart::isValidQtDir( const QString& path ) const
{
    return QFile::exists( path + "/include/qt.h" );
}

QStringList TrollProjectPart::availableQtDirList() const
{
    QStringList qtdirs, lst;
    qtdirs.push_back( ::getenv("QTDIR") );
    qtdirs.push_back( "/usr/lib/qt3" );
    qtdirs.push_back( "/usr/lib/qt" );
    qtdirs.push_back( "/usr/share/qt3" );

    for( QStringList::Iterator it=qtdirs.begin(); it!=qtdirs.end(); ++it )
    {
        QString qtdir = *it;
        if( !qtdir.isEmpty() && isValidQtDir(qtdir) )
	    lst.push_back( qtdir );
    }
    return lst;
}

void TrollProjectPart::setMakeSpec(int i){
    QString base(::getenv("OPIE_SDK_QMAKE_BASE"));
    switch(i){
	case 0:
	    m_makeSpec = base + "linux-ipaq-g++";
	    break;
	case 1:
	    m_makeSpec = base + "linux-sharp-g++";
	    break;
	case 2:
	    m_makeSpec = base + "linux-sharp-big-g++";
	    break;
	case 3:
	    m_makeSpec = base + "linux-simpad-g++";
	    break;
	case 4:
	    m_makeSpec = base + "linux-ramses-g++";
	    break;
	case 5:
	    m_makeSpec = base + "linux-x86-g++";
	    break;
	default:
	case 6:
	    m_makeSpec = base + "linux-generic-g++";
	    break;
	case 7:
	    m_makeSpec = base + "macx-generic-g++";
	    break;
	case 8:
	    m_makeSpec = base + "linux-arm-g++";
	    break;
    };

/* Just work no regards to style
 * Now we need to adjust the Opie and Qt Dir
 */
    switch(i) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 8:
        m_opieOpie = ::getenv("OPIEDIR_ARM");
        m_opieQt   = ::getenv("QTDIR_ARM");
        break;
    case 5:
    case 6:
    case 7:
    default:
        m_opieOpie = ::getenv("OPIEDIR_NAT");
        m_opieQt   = ::getenv("QTDIR_NAT");
        break;
    }
}

void TrollProjectPart::slotQuickLaunch( bool b) {
    kdDebug()<< "Toggle Quick Launch" << endl;
    m_quickLaunch = b;
    DomUtil::writeBoolEntry(*projectDom(), "/kdevtrollproject/opie/quick_app", b );
}

#include "trollprojectpart.moc"
