#include <QTranslator>
#include <QLocale>
#include <QtGui/QApplication>
#include <QDeclarativeEngine>
#include <QString>
#include <QtDeclarative>
#include <QFile>
#include <stdlib.h>

// Define the SQLite database file size.
const int DBSize = 7235584;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);    

    // Detect system locale and loads the Traditional Chinese / Simplified Chinese / English UIs accordingly
    QTranslator translator;
    QString locale = getenv("LANG");

    qDebug() << "Locale = " + locale;


    if (locale == "zh_HK" || locale == "zh_TW" || locale == "zh_MO") {
        // Loading localized translation files from Resources
        translator.load("zh_HK.qm", ":/qml/");
        app.installTranslator(&translator);
    }
    else if (locale == "zh_CN" || locale == "zh_SG") {
        // Loading localized translation files from Resources
        translator.load("zh_CN.qm", ":/qml/");
        app.installTranslator(&translator);
    }


    QDeclarativeView view;

    // Connect the quit signal of QML to Qt's quit signal so that Exit app feature works in QML.

    QObject::connect((QObject*)view.engine(), SIGNAL(quit()), &app, SLOT(quit()));

    // Copy SQLite database over to user's / developer's default local storage path if it does not exist currently.

    QFile UserINIFile("/home/user/.local/share/data/QML/OfflineStorage/Databases/7c78ebb4c223c96f8e6ccc29f73cc28e.ini");
    QFile UserDBFile("/home/user/.local/share/data/QML/OfflineStorage/Databases/7c78ebb4c223c96f8e6ccc29f73cc28e.sqlite");

    QFile DevINIFile("/home/developer/.local/share/data/QML/OfflineStorage/Databases/7c78ebb4c223c96f8e6ccc29f73cc28e.ini");
    QFile DevDBFile("/home/developer/.local/share/data/QML/OfflineStorage/Databases/7c78ebb4c223c96f8e6ccc29f73cc28e.sqlite");

    if ((!UserINIFile.exists() || !UserDBFile.exists() || UserDBFile.size()!=DBSize) && (strcmp(getenv("USER"),"user")==0)) {
            system("cp -f /opt/IMQuery/db/* /home/user/.local/share/data/QML/OfflineStorage/Databases/");
    }

    if ((!DevINIFile.exists() || !DevDBFile.exists() || UserDBFile.size()!=DBSize) && (strcmp(getenv("USER"),"developer")==0)) {
            system("cp -f /opt/IMQuery/db/* /home/developer/.local/share/data/QML/OfflineStorage/Databases/");
    }

    // Load the main QML file for main UI and logics
    view.setSource(QUrl("qrc:/qml/main.qml"));
    view.showFullScreen();
    return app.exec();

}

