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

#include <kysdk/applications/kabase/log.hpp>

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

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

#include "gsettings_monitor.h"
#include "device_monitor.h"
#include "mainwindow.h"
#include "common.h"
#include "find_and_match_ppds.h"
#include "daemonipcdbus.h"
#include "information_collector.h"

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

    //高清屏幕自适应,适配990高DPI
#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0))
  QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
  QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif

    QApplication app(argc, argv);

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

    QStringList cmd = app.arguments();
    cmd.removeFirst();
    if (checkCommand(cmd) == CHECK_FALSE) {
        qDebug() << "UNKNOWN COMMAND:" << cmd;
        return 0;
    }
    //检测单例，调用dbus接口
    QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    int fd = open(QString(homePath.at(0) + "/.config/kylin-printer%1.lock").arg(getenv("DISPLAY")).toUtf8().data(),
                  O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd < 0)
    {
        exit(1);
    }
    if (lockf(fd, F_TLOCK, 0))
    {
        syslog(LOG_ERR, "Can't lock single file, kylin-printer is already running!");
        DaemonIpcDbus* dbus = DaemonIpcDbus::getInstance();
        if(checkCommand(cmd) != CHECK_FALSE) {
            //dbus->request(cmd);
            dbus->callRequest(cmd);
        }
        exit(0);
    }

    //加载中文
    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 = app.applicationDirPath() + "/.qm";
    }

#else
    kylinPrinterTranslationsPath = QString(PROJECT_SOURCE_DIR) + "/translations";
#endif
    qDebug () << kylinPrinterTranslationsPath;
    QString locale = QLocale::system().name();
    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
        app.installTranslator(&trans_global);

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

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

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

    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();
}
