/****************************************************************************
 ** Copyright (C) 2008-2013 Grigory A. Mozhaev <zcrendel@gmail.com>
 **
 ** This file is part of QMultiRecord (http://qt-apps.org/content/show.php?content=106254).
 **
 ** This file may be used under the terms of the GNU General Public
 ** License version 2.0 as published by the Free Software Foundation
 ** and appearing in the file LICENSE.GPL included in the packaging of
 ** this file.  Please review the following information to ensure GNU
 ** General Public Licensing requirements will be met:
 ** http://www.trolltech.com/products/qt/opensource.html
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 ****************************************************************************/
//! -*- coding: UTF-8 -*-
#define SOURCE_CODING "UTF-8"

#include <QtCore>

#include <QMessageBox>

#include "generatedialog.h"
#include "selectdialog.h"

#include "application.h"


Application::Application(int &argc, char **argv) 
    : QApplication(argc,argv)
    , m_generateDialog(0)
{
    setOrganizationName("qmultirecord");
    setApplicationName("qmultirecord");
    setApplicationVersion("0.2.0");
/*
#if HAVE_LOCALE
    initLocale();
#endif // #if HAVE_LOCALE

    Q_ASSERT_X(s_global   != 0, "Application constructor", "Globals pointer is NULL");
*/
}

Application::~Application() {
    if (m_generateDialog) {
        m_generateDialog->setCanClose(true);
        m_generateDialog->deleteLater();
    }
//    if (s_global)  delete s_global;
}

void Application::initLocale() {
    ::setlocale(LC_ALL,"");
    ::setlocale(LC_NUMERIC,"POSIX");

    char *vpLang = ::getenv("LANG");
    if (vpLang != 0 && vpLang[0] != '\0') {
        QLocale vLocale(vpLang);
        QLocale::setDefault(vLocale);
    }

    QTextCodec *vpC = 0;

#ifdef Q_OS_LINUX
    char *vpNlCodeset = ::nl_langinfo(CODESET);
    if (vpNlCodeset!=0 && vpNlCodeset[0] != '\0') {
        vpC = QTextCodec::codecForName(vpNlCodeset);
        if (vpC) 
            QTextCodec::setCodecForLocale(vpC);
    }
#elif defined(Q_OS_WIN32)
    char *vpNlCodeset = "UTF-8";
    vpC = QTextCodec::codecForName(vpNlCodeset);
    if (vpC) 
        QTextCodec::setCodecForLocale(vpC);
#endif

    if (!vpC) {
        vpC = QTextCodec::codecForLocale();
    }
}

Application *Application::instance()
{
    return (static_cast<Application*>(QCoreApplication::instance()));
}

QStringList Application::paths() {
    QSettings settings;
    QStringList active = settings.value("paths").toStringList();
    for (int i=(active.size() - 1); i >= 0; i--) {
        Q_ASSERT(!active.at(i).isEmpty());

        if (active.at(i)[0] == '>') {
            active.removeAt(i);
        }
    }
    return active;
}

void Application::refreshPaths() {
    Q_EMIT(pathsOutdated());
}

void Application::checkMd5SumFiles() {
    if (m_generateDialog) {
        qDebug() << "generate dialog still here, hehe!";
        return ;
    }

    QStringList absentFiles;
    QStringList absentFullNames;

    QStringList rootDirs = Application::paths();
    foreach (QString path, rootDirs) {
        QDir dir(path);
        QStringList categories = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
        foreach (QString category, categories) {
            QDir dir2(QString("%1/%2").arg(path).arg(category));

            QStringList nameFilters;
            nameFilters << QLatin1String("*.[iI][sS][oO]");

            QStringList files = dir2.entryList(nameFilters, QDir::Files);
            foreach (QString file, files) {
                QString fileNameMd5 = QDir::toNativeSeparators(QString("%1/%2/%3.md5sum").arg(path).arg(category).arg(file));
                QFileInfo info(fileNameMd5);
                if (!info.exists()) {
                    absentFiles << QDir::toNativeSeparators(QString("%1/%2").arg(category).arg(file));
                    absentFullNames << QDir::toNativeSeparators(QString("%1/%2/%3").arg(path).arg(category).arg(file));
                }
            }
        }
    }

    if (absentFiles.size() > 0) {
        SelectDialog dialog;
        dialog.setWindowTitle(tr("Select files for which need to generate check Md5 sum"));
        dialog.init(absentFiles);
        if (dialog.exec() == QDialog::Accepted) {
            if (m_generateDialog == 0) {
                m_generateDialog = new GenerateDialog();
                QStringList processFiles, processPaths;
                for (int i=0;i < absentFiles.count(); i++) {
                   if (dialog.isChecked(absentFiles.at(i))) {
                     processFiles << absentFiles.at(i);
                     processPaths << absentFullNames.at(i);
                   }
                }
                connect(m_generateDialog, SIGNAL(destroyed()), this, SLOT(generateDialog_closed()));
                m_generateDialog->setAttribute(Qt::WA_DeleteOnClose, true);
                m_generateDialog->init(processFiles, processPaths);
                m_generateDialog->show();
            }
        }
    } else {
        int ret = QMessageBox::information(0, tr("QMultiRecord"),
                                              tr("No files with missing hashes found."),
                                              QMessageBox::Close,
                                              QMessageBox::Close);
    }
}

void Application::generateDialog_closed() {
    m_generateDialog = 0;
}
