#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QTranslator>
#include <QLocale>
#include <QStandardPaths>
#include <QLibraryInfo>
#include <QDir>
#include <QMetaType>

#include <sys/inotify.h>
#include <fcntl.h>
#include <syslog.h>

#include <QGSettings>
#include <QDir>
#include <QObject>

#include <singleapplication.h>
#include "gsettings_monitor.h"
#include "device_monitor.h"
#include "mainwindow.h"
#include "common.h"
#include "log.h"
#include "find_and_match_ppds.h"
#include "daemonipcdbus.h"
#include "information_collector.h"
#include "windowmanage.hpp"

void addTrans()
{
//加载中文
    QString qtTranslationsPath;
    qtTranslationsPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);// /usr/share/qt5/translations
    QString kylinPrinterTranslationsPath;
#ifndef TEST_DEBUG
    if (QDir("/usr/share/kylin-printer/translations").exists()) {
        kylinPrinterTranslationsPath = "/usr/share/kylin-printer/translations";
    }
    else {
        kylinPrinterTranslationsPath = QApplication::applicationDirPath() + "/.qm";
    }

#else
    kylinPrinterTranslationsPath = QString(PROJECT_SOURCE_DIR) + "/translations";
#endif
    qDebug () << kylinPrinterTranslationsPath;
    QString locale = QLocale::system().name();
    static QTranslator trans_global, trans_menu, trans_dict, trans_sdk;

    if(!trans_global.load("kylin-printer_" + locale + ".qm", kylinPrinterTranslationsPath))
        qDebug() << "Load translations file" <<QLocale() << "failed!";
    else
        QApplication::installTranslator(&trans_global);

    if(!trans_dict.load("kylin-printer_dict_" + locale + ".qm", kylinPrinterTranslationsPath))
        qDebug() << "Load translations file" <<QLocale() << "failed!";
    else
        QApplication::installTranslator(&trans_dict);

    if(!trans_menu.load("qt_" + locale + ".qm", qtTranslationsPath))
        qDebug() << "Load translations file" <<QLocale() << "failed!";
    else
        QApplication::installTranslator(&trans_menu);

    if(!trans_sdk.load(":/translations/gui_" + locale + ".qm"))
        qDebug() << "Load translations file" <<QLocale() << "failed!";
    else
        QApplication::installTranslator(&trans_sdk);
}

int main(int argc, char *argv[])
{
    // 统一日志输出
#ifndef TEST_DEBUG
    qInstallMessageHandler(logOutput);
#else
    qInstallMessageHandler(myMessageOutput);
#endif
    InformationCollector::getInstance().addMessage("打印机应用启动!");
    qRegisterMetaType<ProtocolType>("ProtocolType");
    qRegisterMetaType<DeviceInformation>("DeviceInformation");
    qRegisterMetaType<DeviceInformation>("DeviceInformation&");
    qRegisterMetaType<ppdPrinterMap>("ppdPrinterMap");
    qRegisterMetaType<QString>("QString&");

    //高清屏幕自适应,适配990高DPI
    kabase::WindowManage::setScalingProperties();

    kdk::QtSingleApplication app(argc, argv);

    if (app.isRunning()) {
        qDebug() << "is running";
        app.sendMessage("running , 4000");
        return 0;
    }

    QStringList cmd = app.arguments();
    cmd.removeFirst();
    if (checkCommand(cmd) == CHECK_FALSE) {
        qDebug() << "UNKNOWN COMMAND:" << cmd;
        return 0;
    }

    app.setApplicationVersion("1.3.0");
    app.setWindowIcon(QIcon::fromTheme("kylin-printer"));
    if(!GsettingsMonitor::getInstance()->gsettingsCheck())
    {
        app.setProperty("noChangeSystemFontSize",true);
    }

    addTrans();

    /* 最小化拉起 */
    app.setActivationWindow(MainWindow::getInstance());

    /* wayland 下最小化拉起 */
    if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive)) {
        QObject::connect(&app, &kdk::QtSingleApplication::messageReceived, [=]() {
            if (MainWindow::getInstance()->getWindowId()) {
                kabase::WindowManage::activateWindow(MainWindow::getInstance()->getWindowId());
            }
        });
    }

    QObject::connect(GsettingsMonitor::getInstance(),SIGNAL(sysFontSizeUpdate(QFont)),
                     MainWindow::getInstance(),SLOT(setQSSFontSize(QFont)));
    QObject::connect(MainWindow::getInstance(),SIGNAL(getCurFontSize()),
                     GsettingsMonitor::getInstance(),SLOT(update()));

//    double dFontSize = GsettingsMonitor::getInstance()->initFontSize();
//    qDebug() << dFontSize;
    GsettingsMonitor::getInstance()->update();

    DaemonIpcDbus::getInstance();
    try
    {
        g_findAndMatchWorkThread->start();
    }
    catch(const std::exception& e)
    {
        qFatal("Failed to initial find ppd thread.");
        std::cerr << e.what() << '\n';
        qApp->exit(0);
    }
    g_findAndMatchWorkThread->updatePPDsMap();
    // DeviceMonitor::getInstance()->start();

    DeviceMonitor::getInstance();

    MainWindow::getInstance();//->setQSSFontSize(dFontSize);

    if(checkCommand(cmd) == MAINWINDOW)
    {
        (MainWindow::getInstance())->show();
    }

#if 0
    if(cmd.compare("show")==0)
    {
       wnd.show();
    }else {
       wnd.hide();
    }
    update();
#else
    DeviceMonitor::getInstance()->getarg(cmd);
    // DeviceMonitor::getInstance()->start();
#endif
    return app.exec();
}
