/***************************************************************************
 *   Copyright (C) 2004 by Alexander Dymo                                  *
 *   adymo@kdevelop.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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/
#include "integratordlg.h"

#include <tqfile.h>
#include <tqdir.h>
#include <tqlayout.h>
#include <tqcombobox.h>
#include <tqregexp.h>
#include <tqtextstream.h>
#include <tqcheckbox.h>

#include <tdeapplication.h>
#include <kdialogbase.h>
#include <kurlrequester.h>
#include <kprocess.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kdebug.h>
#include <klineedit.h>

#include <cvsservice_stub.h>

#include "initdlg.h"

IntegratorDlg::IntegratorDlg(CVSServiceIntegrator *integrator, TQWidget *parent, const char *name)
    :IntegratorDlgBase(parent, name), m_integrator(integrator)
{
    TQFile cvspass(TQDir::homeDirPath() + "/.cvspass");
    if (cvspass.open(IO_ReadOnly))
    {
        TQTextStream stream(&cvspass);
        while (!stream.atEnd())
        {
            TQString line = stream.readLine();
            TQStringList recs = TQStringList::split(" ", line, false);
            repository->insertItem(recs[1]);
        }
        cvspass.close();
    }
}

void IntegratorDlg::init_clicked()
{
    KDialogBase dlg(KDialogBase::Plain, i18n("Init CVS Repository"), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok);
    dlg.plainPage()->setMargin(0);
    (new TQVBoxLayout(dlg.plainPage(), 0, 0))->setAutoAdd(true);
    InitDlg *initDlg = new InitDlg(dlg.plainPage());
    initDlg->show();

    initDlg->location->setFocus();
    initDlg->location->setMode(KFile::Directory);
    TQRegExp localrep(":local:(.*)");
    if (localrep.search(repository->currentText()) != -1)
        initDlg->location->setURL(localrep.cap(1));

    if (dlg.exec() == TQDialog::Accepted)
    {
        TQString url = initDlg->location->url();
        TDEProcess *proc = new TDEProcess();
        *proc << "cvs";
        *proc << "-d" << url << "init";
        proc->start(TDEProcess::Block);
        if (!proc->normalExit())
            KMessageBox::error(this, i18n("cvs init did not exit normally. Please check if cvs is installed and works correctly."), i18n("Init CVS Repository"));
        else if (proc->exitStatus() != 0)
            KMessageBox::error(this, i18n("cvs init exited with status %1. Please check if the cvs location is correct.").arg(proc->exitStatus()), i18n("Init CVS Repository"));
        else
        {
            repository->insertItem(TQString(":local:%1").arg(url));
            repository->setCurrentText(TQString(":local:%1").arg(url));
        }
    }
}

void IntegratorDlg::login_clicked()
{
    TQCString appId;
    TQString error;

    if (TDEApplication::startServiceByDesktopName("cvsservice",
        TQStringList(), &error, &appId))
    {
        TQString msg = i18n("Unable to find the Cervisia KPart. \n"
            "Cervisia Integration will not be available. Please check your\n"
            "Cervisia installation and re-try. Reason was:\n") + error;
        KMessageBox::error(this, msg, "DCOP Error");
    }
    else
    {
        CvsService_stub *cvsService = new CvsService_stub(appId, "CvsService");
        cvsService->login(repository->currentText());
    }
}

void IntegratorDlg::accept()
{
    if (m_projectLocation.isEmpty())
        return;

    if (!createModule->isChecked())
        return;

    TDEProcess *proc = new TDEProcess();
    proc->setWorkingDirectory(m_projectLocation);
    *proc << "cvs";
    *proc << "-d" << repository->currentText() << "import"
        << "-m" << TQString("\"%1\"").arg(comment->text()) << module->text()
        << vendorTag->text() << releaseTag->text();
    proc->start(TDEProcess::Block);
    if (!proc->normalExit())
        KMessageBox::error(this, i18n("cvs import did not exit normally. Please check if cvs is installed and works correctly."), i18n("Init CVS Repository"));
    else if (proc->exitStatus() != 0)
        KMessageBox::error(this, i18n("cvs import exited with status %1. Please check if the cvs location is correct.").arg(proc->exitStatus()), i18n("Init CVS Repository"));
    else
    {
        kdDebug() << "Project is in: " << m_projectLocation << endl;

        KURL url = KURL::fromPathOrURL(m_projectLocation);
        TQString up = url.upURL().path();
        kdDebug() << "Up is: " << up << endl;

        //delete sources in project dir
        TDEProcess *rmproc = new TDEProcess();
        *rmproc << "rm";
        *rmproc << "-f" << "-r" << m_projectLocation;
        rmproc->start(TDEProcess::Block);

        //checkout sources from cvs
        TDEProcess *coproc = new TDEProcess();
        coproc->setWorkingDirectory(up);
        *coproc << "cvs";
        *coproc << "-d" << repository->currentText() << "checkout" << "-d" << m_projectName << module->text();
        coproc->start(TDEProcess::Block);
    }

/*    TQCString appId;
    TQString error;

    if (TDEApplication::startServiceByDesktopName("cvsservice",
        TQStringList(), &error, &appId))
    {
        TQString msg = i18n("Unable to find the Cervisia KPart. \n"
            "Cervisia Integration will not be available. Please check your\n"
            "Cervisia installation and re-try. Reason was:\n") + error;
        KMessageBox::error(this, msg, "DCOP Error");
    }
    else
    {
        kdDebug() << "!!!!! IMPORT" << endl;
        CvsService_stub *cvsService = new CvsService_stub(appId, "CvsService");
        cvsService->import(m_projectLocation, repository->currentText(), module->text(),
            "", comment->text(), vendorTag->text(), releaseTag->text(), false);
    }*/
}

void IntegratorDlg::createModule_clicked()
{
}

TQWidget *IntegratorDlg::self()
{
    return const_cast<IntegratorDlg*>(this);
}

void IntegratorDlg::init(const TQString &projectName, const TQString &projectLocation)
{
    if( m_projectName != projectName )
        module->setText(projectName);
    m_projectName = projectName;
    m_projectLocation = projectLocation;
}

#include "integratordlg.moc"
