/***************************************************************************
 * 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 "includes/httraqt.h"
#include "includes/OptionsTab.h"
#include "../options/includes/OptionsDialog.h"
#include "includes/InsertUrlDialog.h"

class InsertUrlDialog;

int OptionsTab::hl01[] = { _MOD00, _MOD01, _MOD02, _MOD03, _MOD04, _MOD05, _MOD06};

OptionsTab::OptionsTab(QWidget *parent, Qt::WindowFlags fl)
    : QWidget(parent, fl)
{
    setupUi(this);

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

    comb01 = LISTDEF_10;

    QString tlist = translate(comb01);
    QStringList lCombo = tlist.split("\n");
    comboAction->insertItems(0, lCombo);

    comboAction->setCurrentIndex(0);
    label03_2->setText(translate(hl01[0]));

    connect(label01, SIGNAL(clicked()), this, SLOT(onSetOptions()));
    connect(label04, SIGNAL(clicked()), this, SLOT(onAddURL()));
    connect(label05_2, SIGNAL(clicked()), this, SLOT(onCaptureUrl()));
    connect(label12, SIGNAL(clicked()), this, SLOT(onURLList()));
    connect(comboAction, SIGNAL(activated(int)), this, SLOT(showHelp()));
    connect(textEdit, SIGNAL(textChanged ()), this, SLOT(removeSpaceLines()));
}


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


void OptionsTab::removeSpaceLines()
{
    QStringList sl;
    bool found = false;
    QString t = textEdit->toPlainText();
    sl = t.split("\n");
    t = "";

    foreach(QString entry, sl) {
        if (entry.length() == 0) {
            found = true;
        }
    }

    if (found == false) {
        return;
    }

    disconnect(textEdit, SIGNAL(textChanged ()), this, SLOT(removeSpaceLines()));

    foreach(QString entry, sl) {
        if (entry.length() > 0) {
            t = t + entry + "\n";
        }
    }

    textEdit->setText(t);

    connect(textEdit, SIGNAL(textChanged ()), this, SLOT(removeSpaceLines()));
}


void OptionsTab::onCaptureUrl()
{
    QClipboard *clipboard = QApplication::clipboard();
    QString originalText = clipboard->text();

    originalText = getAndTestUrlString(originalText);

    if (originalText.length() > 0) {
        originalText += "\n";

        QString st = textEdit->toPlainText();
        st = st + originalText;

        textEdit->setText(st);
    } else {
        MessageBox::exec(this, translate(_ERR), translate(_WRONGURLS), QMessageBox::Warning);
    }
}


void OptionsTab::updateLastAction()
{
    QString dirName = parent->currentWorkDir + "/" + parent->currentProject;

    // il existe déja un cache précédent.. renommer
    if (QFile::exists(dirName + "/hts-cache/new.zip") ||
            (QFile::exists(dirName + "/hts-cache/new.dat") && QFile::exists(dirName + "/hts-cache/new.ndx"))) {
        if (!QFile::exists(dirName + "/hts-cache/interrupted.lock") && !QFile::exists(dirName + "/hts-in_progress.lock")) {
            comboAction->setCurrentIndex(LAST_ACTION);
        } else {
            comboAction->setCurrentIndex(LAST_ACTION - 1);
        }
    }
}


QString OptionsTab::getAndTestUrlString(const QString st)
{
    QUrl u(st);

    if (u.isValid() == true) {
        return st;
    }

    return "";
}


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

    // ajust size(hight) to content
    textEdit->setFixedHeight(textEdit->document()->size().height() + textEdit->contentsMargins().top() * 2);


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

    QString tlist = translate(comb01);
    QStringList lCombo = tlist.split("\n");
    comboAction->clear();
    comboAction->insertItems(0, lCombo);

    label05_2->setText(translate(_GETCLIPBOARD));
    label->setText(translate(_CAPTURL));

    label01->setText(translate(_SET_OPT));
    label02->setText(translate(_ACTION));
    label03->setText(translate(_WEB_ADDR));
    label04->setText(translate(_ADD_URL));
    label05->setText(translate(_URLLIST));
    label06->setText(translate(_PREFS_OPT));

    showHelp();
}


void OptionsTab::onAddURL()
{
    InsertUrlDialog* dUrl = new InsertUrlDialog(parent);

    //     dUrl->setFont(parent->systemFont);
    if (dUrl->exec() == QDialog::Rejected) {
        return;
    }

    QString urlString;

    if (dUrl->m_urllogin.length() == 0) {
        urlString = dUrl->m_urladr;
    } else {
        urlString = dUrl->m_urllogin + ":" + dUrl->m_urlpass + "@" + dUrl->m_urladr;
    }

    urlString = getAndTestUrlString(urlString);

    if (urlString.length() > 0) {
        urlString += "\n";

        QString st = textEdit->toPlainText()/*->text()*/;
        st = st + urlString;

        textEdit->setText(st);
    } else {
        MessageBox::exec(this, translate(_ERR), translate(_WRONGURLS), QMessageBox::Warning);
    }

    delete dUrl;
}


void OptionsTab::showHelp()
{
    int pos = comboAction->currentIndex();
    int origHelpID = hl01[pos];
    QString translated = (translate(origHelpID));
    label03_2->setText(translated);
}


void OptionsTab::onURLList()
{
    QString str = translate(_URLLIST);
    //     QFileDialog fd;
    //     fd = new QFileDialog(this, translate(_OPENFILE), parent->currentWorkDir, str);
    //     fd->setFont(parent->systemFont);
    //     fd->exec();
    QString name = QFileDialog::getOpenFileName(this, translate(_OPENFILE), parent->currentWorkDir, str);

    if (name == "" || name == "/" || name == "\\") {
        return;
    }

    QFile fileName(name);

    if (!fileName.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    QString st = "";

    textEdit->clear();
    label1286->setText("");

    label1286->setText(name);

    QTextStream in(&fileName);
    in.setCodec("UTF-8");

    while (!in.atEnd()) {
        QString line = in.readLine();
        line = getAndTestUrlString(line);

        if (line.length() > 0) {
            st = st + line + "\n";
        }
    }

    fileName.close();

    if (st.length() > 0) {
        textEdit->setText(st);
    } else {
        MessageBox::exec(this, translate(_ERR), translate(_WRONGURLS), QMessageBox::Warning);
    }
}


void OptionsTab::onSetOptions()
{
    OptionsDialog *oDia = new OptionsDialog(parent);
    //     oDia->setFont(parent->systemFont);
    oDia->exec();

    delete oDia;
}


bool OptionsTab::testIt()
{
    QString listOfUrls;
    QStringList urls;
    bool found = false;

    listOfUrls = textEdit->toPlainText();
    urls = listOfUrls.split("\n");

    for (QStringList::Iterator i = urls.begin(); i != urls.end(); i++) {
        QString result;
        result = getAndTestUrlString(*i);

        if (result.length() > 0) {
            found = true;
            break;
        }
    }

    if (found == true) {
        parent->SetProfile("CurrentUrl", listOfUrls);
    } else {
        MessageBox::exec(this, translate(_ERR), translate(_WRONGURLS), QMessageBox::Warning);
    }

    QString urlFile = label1286->text();

    if (urlFile.length() > 0) {
        parent->SetProfile("CurrentURLList", urlFile);
    }

    int action;
    action = comboAction->currentIndex();

    parent->SetProfile("CurrentAction", action);
    return (found);
}



