/*
    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 2 of
    the License or (at your option) version 3 or any later version
    accepted by the membership of KDE e.V. (or its successor approved
    by the membership of KDE e.V.), which shall act as a proxy
    defined in Section 14 of version 3 of the license.


    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 "adddictionary.h"
#include <QFileDialog>
#include "settings.h"
#include <QMessageBox>
#include <QProcess>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

AddDictionary::AddDictionary(QWidget* parent): QDialog(parent)
{
    setupUi(this);
    slotTypeChanged(comboType->currentIndex());
    connect( comboType, SIGNAL(currentIndexChanged(int)),
            this, SLOT(slotTypeChanged(int)) );
    connect( btnBrowse, SIGNAL(clicked(bool)),
             this, SLOT(slotSelectDicFile()) );

    m_NameCode.insert(tr("Afrikaans"), "af");
    m_NameCode.insert(tr("Albanian"), "sq");
    m_NameCode.insert(tr("Arabic"), "ar");
    m_NameCode.insert(tr("Belarusian"), "be");
    m_NameCode.insert(tr("Bulgarian"), "bg");
    m_NameCode.insert(tr("Catalan"), "ca");
    m_NameCode.insert(tr("Chinese"), "zh");
    m_NameCode.insert(tr("Croatian"), "hr");
    m_NameCode.insert(tr("Czech"), "cs");
    m_NameCode.insert(tr("Danish"), "da");
    m_NameCode.insert(tr("Dutch"), "nl");
    m_NameCode.insert(tr("English"), "en");
    m_NameCode.insert(tr("Estonian"), "et");
    m_NameCode.insert(tr("Filipino"), "tl");
    m_NameCode.insert(tr("Finnish"), "fi");
    m_NameCode.insert(tr("French"), "fr");
    m_NameCode.insert(tr("Galician"), "gl");
    m_NameCode.insert(tr("German"), "de");
    m_NameCode.insert(tr("Greek"), "el");
    m_NameCode.insert(tr("Hebrew"), "iw");
    m_NameCode.insert(tr("Hindi"), "hi");
    m_NameCode.insert(tr("Hungarian"), "hu");
    m_NameCode.insert(tr("Icelandic"), "is");
    m_NameCode.insert(tr("Indonesian"), "id");
    m_NameCode.insert(tr("Irish"), "ga");
    m_NameCode.insert(tr("Italian"), "it");
    m_NameCode.insert(tr("Japanese"), "ja");
    m_NameCode.insert(tr("Korean"), "ko");
    m_NameCode.insert(tr("Latvian"), "lv");
    m_NameCode.insert(tr("Lithuanian"), "lt");
    m_NameCode.insert(tr("Macedonian"), "mk");
    m_NameCode.insert(tr("Malay"), "ms");
    m_NameCode.insert(tr("Maltese"), "mt");
    m_NameCode.insert(tr("Norwegian"), "no");
    m_NameCode.insert(tr("Persian"), "fa");
    m_NameCode.insert(tr("Polish"), "pl");
    m_NameCode.insert(tr("Portuguese"), "pt");
    m_NameCode.insert(tr("Romanian"), "ro");
    m_NameCode.insert(tr("Russian"), "ru");
    m_NameCode.insert(tr("Serbian"), "sr");
    m_NameCode.insert(tr("Slovak"), "sk");
    m_NameCode.insert(tr("Slovenian"), "sl");
    m_NameCode.insert(tr("Spanish"), "es");
    m_NameCode.insert(tr("Swahili"), "sw");
    m_NameCode.insert(tr("Swedish"), "sv");
    m_NameCode.insert(tr("Thai"), "th");
    m_NameCode.insert(tr("Turkish"), "tr");
    m_NameCode.insert(tr("Ukrainian"), "uk");
    m_NameCode.insert(tr("Vietnamese"), "vi");
    m_NameCode.insert(tr("Welsh"), "cy");
    m_NameCode.insert(tr("Yiddish"), "yi");

    comboFrom->addItem(tr("Auto"), "auto");
    QMap<QString, QString>::const_iterator it = m_NameCode.constBegin();
    QMap<QString, QString>::const_iterator endIt = m_NameCode.constEnd();
    for(; it != endIt; ++it)
        comboFrom->addItem(it.key(), it.value());
    it = m_NameCode.constBegin();
    for(; it != endIt; ++it)
        comboTo->addItem(it.key(), it.value());
}

AddDictionary::~AddDictionary()
{

}

void AddDictionary::slotSelectDicFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Select Database"), QString(),
                       tr("MDic Dictionary database(*.m2 *.mdb *.m2.bz2 *.m2.gz *.mdb.bz2 *.mdb.gz);;All files(*)"));
    if( !filePath.isEmpty() )
        txtFilePath->setText(filePath);
}

void AddDictionary::accept()
{
    if(comboType->currentIndex() == 0) {
        QString filePath = txtFilePath->text();
        if (!filePath.isEmpty()) {
            QFileInfo infoFile(filePath);
            QFile dbfile(filePath);
            QString FileName = infoFile.fileName();
            QString newFilePath = Settings::self()->dbsDir() + FileName;
            if (QFile::exists(newFilePath))
                QFile::remove(newFilePath);

            if (!dbfile.copy(newFilePath)) {
                QMessageBox::critical(this, tr("Error!"),
                                    tr("Can not use selected file,\n%1").arg(dbfile.errorString()));
            } else {
                if (FileName.right(4) == ".bz2") {
                    QProcess::execute("bunzip2", QStringList(Settings::self()->dbsDir() + FileName));
                    FileName.remove(FileName.length() - 4, 4);
                }
                if (FileName.right(3) == ".gz") {
                    QProcess::execute("gunzip", QStringList(Settings::self()->dbsDir() + FileName));
                    FileName.remove(FileName.length() - 3, 3);
                }

                QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", FileName);
                db.setDatabaseName(Settings::self()->dbsDir() + FileName);
                if (!db.open()) {
                    QMessageBox::critical(this, tr("Cannot Add Database File"),
                                        tr("Cannot open database file, it seems it's not a typical MDic Database file...\n%1").arg(db.lastError().text()));
                    QFile::remove(Settings::self()->dbsDir() + FileName);
                } else {
                    QSqlQuery q(db);
                    q.exec("select * from word limit 1");
                    if (!q.next()) {
                        QMessageBox::critical(this, tr("Cannot Add Database File"),
                                            tr("It seems, it's not a typical MDic Database file.\nCheck it and try again...\n%1").arg(db.lastError().text()));
                        QFile::remove(Settings::self()->dbsDir() + FileName);
                    } else {
                        m_resultDict.setBackendType(DictCore::MDic);
                        m_resultDict.setName(FileName);
                        m_resultDict.setCode(FileName);
                        m_resultDict.setEnabled();
                        QDialog::accept();///It's OK
                    }
                }
            }
        } else {
            QMessageBox::warning(this, tr("Warning"), tr("Dictionary file name is empty."));
        }
    } else if(comboType->currentIndex() == 1){
        QString code = comboFrom->itemData(comboFrom->currentIndex()).toString() + '|' + comboTo->itemData(comboTo->currentIndex()).toString();
        m_resultDict.setBackendType(DictCore::GoogleTranslate);
        m_resultDict.setCode(code);
        m_resultDict.setEnabled(true);
        m_resultDict.setName( comboFrom->currentText() + "->" + comboTo->currentText() );
        QDialog::accept();
    }
}

void AddDictionary::slotTypeChanged(int index)
{
    switch(index){
    case 0:
        groupGTranslate->hide();
        groupMDic->show();
        break;
    case 1:
        groupGTranslate->show();
        groupMDic->hide();
        break;
    }
}

DictCore::Dictionary AddDictionary::resultDict()
{
    return m_resultDict;
}

#include "adddictionary.moc"
