/*
   This file is part of MDic Dictionary

   Copyright (C) 2007-2010 Mehrdad Momeny <mehrdad.momeny@gmail.com
   Copyright (C) 2007-2010 Majid Ramezanpour <majid.ramezanpour@gmail.com>

   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 3 of the License,
   (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, see http://www.gnu.org/licenses/

*/

#include "mdicconv.h"

#include <QFileInfo>
#include <QFileDialog>
#include <QProcess>
#include <QMessageBox>
#include <QDebug>

MDicConv::MDicConv(QWidget *parent)
        : QDialog(parent)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setupUi(this);
    btnAdd->hide();
    p = new QProcess(qApp);
    pTimer.setInterval(500);
    success = false;

    connect(btnBrowse, SIGNAL(clicked()), this, SLOT(sltBrowseFile()));
    connect(btnBrowse_2, SIGNAL(clicked()), this, SLOT(sltBrowseMDicConv()));
    connect(btnConvert, SIGNAL(clicked()), this, SLOT(sltConvert()));
    connect(txtMDicConv, SIGNAL(textChanged(QString)), this, SLOT(sltCheckPath(QString)));
    connect(&pTimer, SIGNAL(timeout()), this, SLOT(sltTimer()));
    connect(p, SIGNAL(finished(int)), this, SLOT(sltProcessExited(int)));
    connect(chkSameAsSource, SIGNAL(toggled(bool)), this, SLOT(sltDirChanged(bool)));
    connect(btnBrowse_Dest, SIGNAL(clicked()), this, SLOT(sltBrowseDestDir()));

    txtMDicConv->setText("/usr/local/bin/mdicconv");
}

void MDicConv::sltBrowseMDicConv()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Select MDicConv Executable..."));
    txtMDicConv->setText((filePath == "") ? txtMDicConv->text() : filePath);
}

void MDicConv::sltBrowseFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Select a dictionary to convert"), txtSource->text(), tr("Supported dictionaries (*.ifo *.bgl *.tei *.dct)"));
    txtSource->setText((filePath == "") ? txtSource->text() : filePath);
    if (QFile::exists(txtSource->text())) {
        QFileInfo srcFile(txtSource->text());
        txtDestName->setText(srcFile.completeBaseName());
    }
}

void MDicConv::sltConvert()
{
    if (isPathOK && QFile::exists(txtSource->text())) {
        QString outSuffix = ".m2";
        QString destDir;
        QFileInfo srcFile(txtSource->text());
        if (chkSameAsSource->isChecked())
            destDir = srcFile.dir().absolutePath();
        else if ( !txtDest->text().isEmpty() && QFile::exists(txtDest->text()) )
            destDir = txtDest->text();
        QString srcFileName = (txtDestName->text() == "" ? srcFile.completeBaseName() : txtDestName->text());

        int number = 0;
        QString txtNo;
        while (QFile::exists(destDir + '/' + srcFileName + txtNo + outSuffix))
            txtNo = QVariant(number++).toString();
        destFile = destDir + '/' + srcFileName + txtNo + outSuffix;

        QStringList l;
        l.append("-o");
        l.append(destFile);
        l.append(txtSource->text());
        p->start(txtMDicConv->text(), l, QProcess::ReadOnly);
        pTimer.start();
//             QString str="";
//             for(int i=0; i<l.count(); i++)
//                 str+=l[i];
//             qDebug(str.toLatin1().data());
        lblOutput->setStyleSheet("QLineEdit{color:black}");
        lblOutput->setText(tr("Converting. "));
        counter = 1;
        txtSource->setEnabled(false);
    } else
        QMessageBox::warning(this, tr("Invalid input file"), tr("Please specify a valid input file and specify valid path for mdicconv binary!"));
}

void MDicConv::sltAddDb()
{
//     if(success){
//         QString FileName = QFileInfo(destFile).fileName;
//         if(!QFile::copy(destFile, config->DBsDir()+ FileName));{
//             QMessageBox::warning(this, tr("Error!"), tr("Can not copy created file, check errors:\n") + QFile::errorString());
//             return;
//             }
//         QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", FileName);
//
//         db.setDatabaseNameconfig->(DBsDir() +FileName);
//
//         if(!db.open())
//             {QMessageBox::warning(this, "Cannot Add Database File", "Cannot open database file, it seems it's not a typical MDic Database file...");
//             QFile::remove(config->DBsDir() +FileName);}
//         else
//         {
//             QSqlQuery q(db);
//             q.exec("select * from word limit 1");
//             if(!q.next())
//             {
//                 QMessageBox::warning(this, "Cannot Add Database File", "It seems, it's not a typical MDic Database file.\nCheck it and try again...");
//                 QFile::remove(config->DBsDir() +FileName);
//             }
//             else
//                 config->LoadDB(FileName,1);
//         }
//     }
//     else
//         QMessageBox::warning(this, "Cannot add!", "First convert your dictioanry.");
}

void MDicConv::sltCheckPath(const QString &path)
{
    QFileInfo f(path);
    if (f.exists() && (f.isFile() || f.isSymLink()) && f.isExecutable() && f.isReadable()) {
        txtMDicConv->setStyleSheet("QLineEdit{color:green}");
        isPathOK = true;
    } else {
        txtMDicConv->setStyleSheet("QLineEdit{color:red}");
        isPathOK = false;
    }
}

void MDicConv::sltTimer()
{
    counter++;
    if (counter == 10) {
        lblOutput->setText(tr("Converting. "));
        counter = 0;
    } else
        lblOutput->setText(lblOutput->text() + ". ");

    std::string s(p->readAllStandardOutput().data());
    QString output = s.c_str();
    qDebug() << output;
    logger->append(output);
}

void MDicConv::sltProcessExited(int result)
{
    std::string s(p->readAllStandardOutput().data());
    QString output = s.c_str();
    qDebug() << output;
    logger->append(output);
    pTimer.stop();
    qDebug("MDicConv::sltProcessExited: process finished with status code %d", result);
    if (result != 1) {
        QMessageBox::information(this, tr("Success!"), tr("Database converted successfully.\nyou can find it here: \n") + destFile);
        txtSource->setEnabled(true);
        lblOutput->setStyleSheet("QLabel{color:green;}");
        lblOutput->setText("Success!");
        success = true;
    } else {
        QMessageBox::critical(this, tr("Failed!"), tr("Process failed,\nplease check output Log!\n if error is \"Error openning iconv library\" change output file name."));
        txtSource->setEnabled(true);
        lblOutput->setStyleSheet("QLabel{color:red;}");
        lblOutput->setText(tr("Failed!"));
        success = false;
    }
}

void MDicConv::sltLog(bool flg)
{
    if (flg)
        logger->show();
    else
        logger->hide();
}

void MDicConv::sltBrowseDestDir()
{
    QString path = QFileDialog::getExistingDirectory(this, tr("Select destination directory"), txtDest->text());
    txtDest->setText(path);

}

void MDicConv::sltDirChanged(bool flg)
{
    txtDest->setEnabled(!flg);
    btnBrowse_Dest->setEnabled(!flg);
    if (!flg && txtDest->text().isEmpty())
        txtDest->setText(QFileInfo(txtSource->text()).dir().absolutePath());
}

#include "mdicconv.moc"
