/***************************************************************************
 *   Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr  *
 *                                                                         *
 *   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) 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/>  *
 ***************************************************************************/
/** @file
* This file defines the main of skroogeconvert.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgdocumentbank.h"
#include "skgtransactionmng.h"
#include "skgimportexportmanager.h"
#include "skgtraces.h"

#include <kaboutdata.h>

#include <qurl.h>

#include <QCoreApplication>
#include <qfileinfo.h>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <qapplication.h>

/**
 * To compute the version
 */
#define VER1_(x) #x
/**
 * To compute the version
 */
#define VER_(x) VER1_(x)
/**
 * To compute the version
 */
#define VER VER_(SKGVERSION)


/**
 * The main of the application
 * @param argc number of arguments
 * @param argv arguments
 * @return return code
 */
int main(int argc, char** argv)
{
    KLocalizedString::setApplicationDomain("skrooge");

    KAboutData about("skroogeconvert",
                     i18nc("The name of the application", "Skrooge Convert"),
                     VER,
                     i18nc("The description of the application", "A conversion tool for financial files (KMyMoney, GnuCash, Skrooge, ...)"),
                     KAboutLicense::GPL_V3,
                     i18nc("Fullname", "(c) 2007-%1 Stephane MANKOWSKI & Guillaume DE BURE", QDate::currentDate().toString("yyyy")),
                     "",
                     "http://skrooge.org");

    about.addAuthor(i18nc("Fullname", "Stephane MANKOWSKI"), i18nc("A job description", "Architect & Developer"), "stephane@mankowski.fr", ""
                    , "miraks"
                   );
    about.addAuthor(i18nc("Fullname", "Guillaume DE BURE"), i18nc("A job description", "Developer"), "guillaume.debure@gmail.com", ""
                    , "willy9"
                   );
    about.setOtherText(i18nc("The description of the application", "The application name is inspired by Charles Dicken's tale <i>A Christmas Carol</i>, where the main character, Ebenezer Scrooge, a grumpy old narrow man, gets visited by three ghosts who change the way he sees the world, in a good way."));
    about.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));
    KAboutData::setApplicationData(about);

    QCoreApplication app(argc, argv);
    app.setApplicationName(about.componentName());
    app.setOrganizationDomain(about.organizationDomain());
    app.setApplicationVersion(about.version());

    QCommandLineParser parser;
    parser.addVersionOption();
    parser.addHelpOption();

    parser.addOption(QCommandLineOption(QStringList() << "in", i18nc("Application argument", "Input file. Supported formats:\n%1", SKGImportExportManager::getImportMimeTypeFilter(false)), "file"));
    parser.addOption(QCommandLineOption(QStringList() << "out", i18nc("Application argument", "Output file. Supported formats:\n%1", SKGImportExportManager::getExportMimeTypeFilter(false)), "file"));
    parser.addOption(QCommandLineOption(QStringList() << "param", i18nc("Application argument", "Name of a parameter"), "name"));
    parser.addOption(QCommandLineOption(QStringList() << "value", i18nc("Application argument", "Value of a parameter"), "value"));

    about.setupCommandLine(&parser);
    parser.process(app);
    about.processCommandLine(&parser);


    // Build list of arguments
    SKGError err;
    if (!parser.isSet("in")) {
        err = SKGError(ERR_INVALIDARG, i18nc("Error message", "Missing -in option"));
    } else if (!parser.isSet("out")) {
        err = SKGError(ERR_INVALIDARG, i18nc("Error message", "Missing -out option"));
    }

    // Initialisation of a bank document
    SKGDocumentBank document;
    document.setComputeBalances(false);
    IFOKDO(err, document.initialize())
    IFOK(err) {
        // Import
        QString file = parser.value("in");
        QFileInfo fi(file);
        if (fi.exists()) {
            file = fi.absoluteFilePath();
        }
        SKGImportExportManager imp(&document, QUrl::fromLocalFile(file));
        QMap<QString, QString>  parameters = imp.getImportParameters();
        QStringList params = parser.values("param");
        QStringList values = parser.values("value");
        int nb = qMin(params.count(), values.count());
        for (int i = 0; i < nb; ++i) {
            parameters[params.at(i)] = values.at(i);
        }
        imp.setImportParameters(parameters);

        SKGTRACESEPARATOR;
        SKGTRACE << i18nc("Title of a console trace section", " Import parameters") << endl;
        QMapIterator<QString, QString> i(imp.getImportParameters());
        while (i.hasNext()) {
            i.next();
            SKGTRACE << " " << i.key() << "=" << i.value() << endl;
        }
        SKGTRACESEPARATOR;
        SKGTRACE << i18nc("Title of a console trace section", " Imported file:") << imp.getFileName().toDisplayString()  << endl;
        if (fi.suffix().toUpper() == "SKG" || fi.suffix().toUpper() == "SQLITE" || fi.suffix().toUpper() == "SQLCIPHER") {
            err = document.load(file, parameters["password"]);
        } else {
            SKGBEGINTRANSACTION(document, "IMPORT", err);
            IFOKDO(err, imp.importFile())
        }
    }
    IFOK(err) {
        // Export
        QString file = parser.value("out");
        QFileInfo fi(file);
        if (fi.exists()) {
            file = fi.absoluteFilePath();
        }
        SKGImportExportManager exp(&document, QUrl::fromLocalFile(file));
        SKGTRACESEPARATOR;
        SKGTRACE << i18nc("Title of a console trace section", " Exported file:") << exp.getFileName().toDisplayString()  << endl;
        if (fi.suffix().toUpper() == "SKG") {
            err = document.saveAs(file, true);
        } else {
            err = exp.exportFile();
        }
    }

    // Dump getMessages
    QList<SKGDocument::SKGMessage> oMessages;
    IFOKDO(err, document.getMessages(document.getCurrentTransaction(), oMessages));
    int nb = oMessages.count();
    if (nb > 0) {
        SKGTRACESEPARATOR;
        for (int i = 0; i < nb; ++i) {
            SKGTRACE << oMessages.at(i).Text << endl;
        }
    }

    IFKO(err) {
        SKGTRACESUITE << err.getFullMessageWithHistorical() << endl;
        SKGTRACESEPARATOR;
        SKGTRACE << i18nc("Title of a console trace section", " FAILED") << endl;
        SKGTRACESEPARATOR;
    } else {
        SKGTRACESEPARATOR;
        SKGTRACE << i18nc("Title of a console trace section", " SUCCESSFUL") << endl;
        SKGTRACESEPARATOR;
    }

    SKGTraces::dumpProfilingStatistics();
    return err.getReturnCode();
}
