#include "mapplication.h"
#include "src/gui/mainwindow.h"
#include "sqltable.h"
#include "dialogcreateenterprise.h"
#include "dialogopencompany.h"

#include <QtSql>
#include <QSettings>


MApplication::MApplication(int &argc, char** argv):
    QApplication(argc, argv)
{
    //QFont f = this->font();
    //f.setPointSize(10);
    //setFont(f);

    //QString map = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    mDataFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    mConfigFolder = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);

    if (!mDataFolder.endsWith(QDir::separator()))
        mDataFolder += QDir::separator();

    QDir dir;
    if ( !dir.exists(mDataFolder))
        dir.mkpath(mDataFolder);

    mSettings = new QSettings (applicationName(), "settings");
    if (!QFile(mSettings->fileName()).exists())
    {
        //resetSettings();
    }

    initDB();
}

MApplication::~MApplication()
{
    if(EnterpriseDB.isOpen())
        EnterpriseDB.close();

    if(EnterpriseListDB.isOpen())
        EnterpriseListDB.close();
}

QString MApplication::dataFolder()
{
    return mDataFolder;
}

QString MApplication::configFolder()
{
    return mConfigFolder;
}

QSqlDatabase MApplication::EnterpriseList()
{
    return EnterpriseListDB;
}

QSqlDatabase MApplication::Enterprise()
{
    return EnterpriseDB;
}

void MApplication::listCompanies()
{
    EnterpriseListDB.open();
    QSqlQuery *qry = new QSqlQuery(EnterpriseListDB);
    bool done = qry->exec("SELECT * FROM ENTERPRISES;");
    EnterpriseListDB.close();

    int cnt = 0;
    if (done)
    {
        while(qry->next())
        {
            cnt ++;
        }
    }
    else
    {
        qDebug() << "Error ejecutando el query: " << qry->lastError().text() << "\n";
        return;
    }

    if(cnt > 0)
    {
        // 1. Si sólo es una la abrimos directamente
        /*
        if(cnt == 1)
        {
            openCompany(qry->value(1).toString());
            return;
        }
        */

        // 2. Si hay más de dos empresas abrimos la lista de empresas
        dialogOpenCompany *dOpenCompany = new dialogOpenCompany();
        qry->first();
        do
        {
            dOpenCompany->setData(qry->value(0).toString(),
                                  qry->value(1).toString(),
                                  //qry->value(2).toString(),
                                  qry->value(3).toString()
                                  //qry->value(4).toString()
                                  );

        } while(qry->next());

        dOpenCompany->exec();
        return;
    }

    dialogCreateEnterprise *creator = new dialogCreateEnterprise();
    creator->exec();
}

bool MApplication::openCompany(QString ID)
{
    QString path = mDataFolder + ID + QDir::separator() + ID + ".db";

    if (!QSqlDatabase::drivers().contains("QSQLITE"))
    {
        /*
        DDialog msgBox;
        msgBox.setWindowModality(Qt::WindowModal);
        //msgBox.setWindowTitle(tr("Save Draft?"));
        msgBox.setIcon(QIcon::fromTheme("dialog-information"));
        QString message("No es posible crear/cargar la base de datos.<br>"
                        "No se encuentra el driver SQLITE.");
        msgBox.setMessage(message);
        msgBox.addButton ("OK", true, DDialog::ButtonRecommend);
        msgBox.exec();
        */
        return false;
    }

    EnterpriseDB = QSqlDatabase::addDatabase("QSQLITE", ID);
    EnterpriseDB.setDatabaseName(path);

    if(!EnterpriseDB.open())
        return false;

    //TODO: leer los datos basicos de la compañia y ponerlos donde corresponda:
    /*
    QStringList tables = EnterpriseDB.tables();
    QSqlQuery *qry = new QSqlQuery(EnterpriseDB);
    if (!tables.contains("ENTERPRISES", Qt::CaseInsensitive))
    {
        if (!qry->exec(tEmpresas))
        {
            qDebug() << "Error ejecutando el query: " << qry->lastError().text() << "\n";
            return false;
        }
    }
    */

    EnterpriseDB.close();

    mwindow->setCompany(ID);
}

bool MApplication::closeCompany()
{
    //TODO: cerrar todos los formularios y dialogos abiertos>

    //TODO: Cerrar y eliminar la conexión:
    QSqlDatabase::removeDatabase(EnterpriseDB.connectionName());
}

void MApplication::setMainWindow(MainWindow *val)
{
    mwindow = val;
}

MainWindow *MApplication::mainWindow()
{
    return mwindow;
}

void MApplication::initDB()
{
    //sql:
    if (!QSqlDatabase::drivers().contains("QSQLITE"))
    {
        /*
        DDialog msgBox;
        msgBox.setWindowModality(Qt::WindowModal);
        //msgBox.setWindowTitle(tr("Save Draft?"));
        msgBox.setIcon(QIcon::fromTheme("dialog-information"));
        QString message("No es posible crear/cargar la base de datos.<br>"
                        "No se encuentra el driver SQLITE.");
        msgBox.setMessage(message);
        msgBox.addButton ("OK", true, DDialog::ButtonRecommend);
        msgBox.exec();
        */
        return;
    }

    EnterpriseListDB = QSqlDatabase::addDatabase("QSQLITE", "ENTERPRISES");
    EnterpriseListDB.setDatabaseName(dApp->dataFolder() + "ENTERPRISES.db");

    if(!EnterpriseListDB.open())
        return;

    QStringList tables = EnterpriseListDB.tables();
    QSqlQuery *qry = new QSqlQuery(EnterpriseListDB);
    if (!tables.contains("ENTERPRISES", Qt::CaseInsensitive))
    {
        if (!qry->exec(tEmpresas))
        {
            qDebug() << "Error ejecutando el query: " << qry->lastError().text() << "\n";
            return;
        }
    }

    if (!tables.contains("DBINFO", Qt::CaseInsensitive))
    {
        if (!qry->exec(tDBInfo))
        {
            qDebug() << "Error ejecutando el query: " << qry->lastError().text() << "\n";
            return;
        }
        qry->prepare(DBInfoCommand);
        qry->bindValue(":VERSION", dApp->applicationVersion().isEmpty() ? "0" : dApp->applicationVersion());
        qry->bindValue(":SUBVERSION", "0");
        if (!qry->exec())
        {
            qDebug() << "Error ejecutando el query: " << qry->lastError().text() << "\n";
            return;
        }
    }
    EnterpriseListDB.close();
}

