/***************************************************************************
 * C++ Implementation:                                                     *
 * Copyright (C) 2012-2017 by Eduard Kalinowski                            *
 * Germany, Lower Saxony, Hanover                                          *
 * eduard_kalinowski@yahoo.de                                              *
 *                                                                         *
 * HTTraQt is free software; may be distributed and/or modified under the  *
 * terms of the GNU General Public License version 3 as published by the   *
 * Free Software Foundation and appearing in the file LICENSE_GPLv3        *
 * included in the packaging of this file.                                 *
 *                                                                         *
 * 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 Lesser General Public        *
 * License along with HTTraQt. If not, see  http://www.gnu.org/licenses    *
 ***************************************************************************/

#include <QtGui>
#include <QFileDialog>
#include <unistd.h>


#include "includes/NewProjTab.h"
#include "../version.h"


NewProjTab::NewProjTab(QWidget* parent, Qt::WindowFlags fl)
    : QWidget(parent, fl)
{

    setupUi(this);

    this->parent = static_cast<HTTraQt*>(parent);

    label02->setEnabled(false);    // project category disabled
    comboProjCat->setEnabled(false);    // selection too

    //     setStyleSheet(this->parent->programStyleSheet);

    connect(editBasePath, SIGNAL(textChanged(QString)), this, SLOT(workDirChanged()));
    connect(comboProjName->lineEdit(), SIGNAL(returnPressed()), this, SLOT(projectInfoEntered()));
    connect(comboProjName, SIGNAL(activated(int)), this, SLOT(projectInfoSelected()));
    connect(label1228, SIGNAL(clicked()), this, SLOT(onBrowseProject()));
}


void NewProjTab::translateTab(void)
{
    setMinimumSize(410, 250);

    if (parent->programStyleSheet.length() > 0) {
        setStyleSheet(parent->programStyleSheet);
    }

    label01->setText(translate(_PROJNAME));
    label02->setText(translate(_PROJCAT));
    label04->setText(translate(_BASEPATH));
    label03->setText(translate(_TYPENEWPROJ));
}


NewProjTab::~NewProjTab()
{
    //   cout << "will be deleted" << endl;
}


void NewProjTab::resizeEvent(QResizeEvent *event)
{
}

bool NewProjTab::testIt()
{
    QString baseDir = editBasePath->text();

    if (baseDir.length() <= 0) {
        MessageBox::exec(this, translate(_NODIR), translate(_TYPENEWPROJ), QMessageBox::Critical);
        return (false);
    }

    QDir verz(baseDir);

    if (verz.exists() == false) {
        if (verz.mkdir(baseDir) == false) {
            MessageBox::exec(this, translate(_CREATEERR), translate(_CANOTCREATEDIR), QMessageBox::Critical);

            return (false);
        }
    }

    parent->currentWorkDir = baseDir;

    QString projName = comboProjName->currentText();

    if (projName.length() <= 0) {
        MessageBox::exec(this, translate(_NOPROJ), translate(_TYPENEWPROJ), QMessageBox::Critical);

        return (false);
    }

    QString newPrDir = baseDir + "/" + projName + "/hts-cache/";
    parent->currentProject = projName;
    //     qDebug() << "new projtab" << projName;

    QDir dr(newPrDir);

    if (dr.exists() == false) {
        if (dr.mkpath(newPrDir) == false) {
            MessageBox::exec(this, translate(_CREATEERR), translate(_CANOTCREATEDIR), QMessageBox::Critical);

            return false;
        }
    }

    parent->getOptions();

    parent->writeSettings(false);

    parent->setWindowTitle(QString(PROGRAM_NAME) +  " v." + HTTQTVERSION + " , " + translate(_PROJ) + ": " + parent->currentProject);

    return (true);
}


void NewProjTab::rebuildDirList()
{
    currentsubdirs.clear();
    comboProjName->clear();

    QFileInfoList finfolist;
    QDir dr(parent->currentWorkDir);
    dr.setNameFilters(QStringList("*"));
    dr.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
    finfolist = dr.entryInfoList();

    for (int i = 0; i < finfolist.size(); ++i) {
        QString tmpNm =  finfolist.at(i).fileName();

        if (QFile::exists(parent->currentWorkDir + "/" + tmpNm + "/linprofile.ini") == true ||
                QFile::exists(parent->currentWorkDir + "/" + tmpNm + "/hts-cache/winprofile.ini") == true ) {
            currentsubdirs << tmpNm;
        }
    }

    if (editedName.size() > 0) {
        if (currentsubdirs.indexOf(editedName) == -1) {
            currentsubdirs << editedName;
        }
    }

    if (currentsubdirs.size() > 0) {
        int ind;
        comboProjName->setDuplicatesEnabled(false);
        comboProjName->addItems(currentsubdirs);
        ind = comboProjName->findText(editedName);

        if (ind >= 0) {
            comboProjName->setCurrentIndex(ind);
        }
    }
}


void NewProjTab::onBrowseProject()
{
    QString t = editBasePath->text();

    if (t.length() < 1) {
        t = parent->currentWorkDir;
    }

    QString s = QFileDialog::getExistingDirectory(this, translate(_SELECTPATH), t,
                QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks/* |  QFileDialog::DontUseNativeDialog*/);


    if (s.length() <= 0) {
        return;
    }

    QDir dd(s);

    if (dd.exists() == false) {
        return;
    }

    parent->currentWorkDir = s;

    parent->writeSettings(true);

    editBasePath->setText(s);

    parent->dirView->reset();

    parent->dirView->setRootIndex(parent->dModel.index(s));

    editedName = "";

    rebuildDirList();
}


void NewProjTab::workDirChanged()
{
    QString dr = editBasePath->text();
    QDir d(dr);

    if (d.exists() == false) {
        return;
    }

    rebuildDirList();

    parent->dirView->setRootIndex(parent->dModel.index(dr));
}

#if 0
void NewProjTab::onSelectBatchFile()
{
    QFileDialog* fd;
    int sz = parent->systemFont.pointSize();
    QString sSheet;
    sSheet = QString().sprintf("font-size: %dpt", sz);

    if ( sz == -1) {
        sz = parent->systemFont.pixelSize();
        sSheet = QString().sprintf("font-size: %dpx", sz);
    }

    setStyleSheet(sSheet);

    fd = new QFileDialog(this, translate("Choose a file"), parent->currentWorkDir, "Text (*.txt)");
    //     fd->setFont(parent->systemFont);
    //     fd->exec();
    QString s = fd->getOpenFileName();//QFileDialog::getOpenFileName(this, translate("Choose a file"), parent->currentWorkDir, "Text (*.txt)");
}
#endif

void NewProjTab::projectInfoEntered()
{
    QString temp = comboProjName->currentText();

    editedName = temp;
}

void NewProjTab::selectProj(const QString &name)
{
    int pos = comboProjName->findText(name);

    if (pos >= 0) {
        comboProjName->setCurrentIndex(pos);
        emit projectInfoSelected();
    }
}

void NewProjTab::projectInfoSelected()
{
    bool exists = false;

    //     disconnect(editBasePath, SIGNAL(textChanged (QString)), this, SLOT(projectInfoSelected()));

    QString temp = comboProjName->currentText();

    editedName = temp;

    parent->currentProject = temp;

    QString fileName = parent->currentWorkDir + "/" + temp;
    QDir dir = fileName;

    if (QFile::exists(fileName + "/linprofile.ini")) {
        if (dir.exists() == true) {
            exists = true;
        }
    }

    if (QFile::exists(fileName + "/hts-cache/winprofile.ini")) {
        if (dir.exists() == true) {
            exists = true;
        }
    }

    if (exists == false) {
        //         parent->readSettings(true);
        label03->setText(translate(_NEWPROJECT));

    } else {
        label03->setText(translate(_TYPENEWPROJ));
    }

    parent->getOptions();

    changeProjname(fileName);

    //     connect(editBasePath, SIGNAL(textChanged (QString)), this, SLOT(projectInfoSelected()));
}

void NewProjTab::onDirChanged()
{
    QString dir = editBasePath->text();
    QDir dd(dir);

    if (dd.exists() == true) {
        // opren dir in file browser
        rebuildDirList();
    }
}


void NewProjTab::changeProjname(QString stl)      //kompletter name
{
    QString st;
    bool found = false;
    QString tempName;
    //

    if (stl.length() == 0 || stl.length() > HTS_URLMAXSIZE) {
        label03->setText(translate(_TYPENEWPROJ));
        label01->setText(translate(_PROJNAME));
    } else {
        st = editBasePath->text(); // current Directory

        tempName = (stl + "/linprofile.ini");

        QFile setlin(tempName);

        if (setlin.exists() == true  &&  // un cache est pr�sent
                (setlin.size()) > 0) {      // taille log contr�le>0
            found = true;
        } else {
            tempName = (stl + "/hts-cache/winprofile.ini");
            QFile setwin(tempName);

            if (setwin.exists() == true  &&  // un cache est pr�sent
                    (setwin.size()) > 0) {      // taille log contr�le>0
                found = true;
            }
        }

        if (found == false) {
            //             parent->readSettings(true);
            label03->setText(translate(_NEWPROJECT));
            label01->setText(translate(_NEWPROJNAME));
            //      parent->m_todo = 0;
        } else {
            parent->GetProfile("CurrentUrl", st);
            parent->GetProfile("Category", stl);
            //
            label03->setText(st);
            label01->setText(translate(_PROJNAME));
        }

    }

    parent->currentOptionsFile = tempName;

    rebuildDirList();
}




