#include "src/view/mainwindow.h"
#include "src/frame/configuration.h"
#include "src/frame/logger.h"
#include "src/model/logicmain.h"
#include "src/model/monitorcdrom.h"
#include "src/model/menufactory.h"
#include "src/model/logiccopyimage.h"
#include "src/view/modaldialog.h"
#include "src/view/aboutdialog.h"
#include "src/view/execdialog.h"
#include "src/view/filefilterrules.h"
#include "src/view/viewfilterfiles.h"
#include "src/view/tip_burnresult.h"
#include "src/po/translation.h"
#include "src/common/utils.h"

#include <QScreen>
#include <QObject>
#include <QApplication>
#include <QDesktopWidget>
#include <QCommandLineParser>
#include <ukui-log4qt.h>
#include <QTranslator>
#include <QLibraryInfo>
#include <kwidget.h>
#include <ukuistylehelper/ukuistylehelper.h>
#include <windowmanager/windowmanager.h>
#include <kysdk/diagnosetest/libkydatacollect.h>
#include <kysdk/applications/singleapplication.h>
#include <QTranslator>
#include <QDBusReply>
#include <QDBusInterface>
using namespace kdk;

int main(int argc, char *argv[])
{
    //判断是否是wayland环境
    bool isWayland = false;
    if(QString(qgetenv("XDG_SESSION_TYPE")) == "wayland") {
        //qputenv("QT_QPA_PLATFORM", "wayland");
        qputenv("QT_WAYLAND_SHELL_INTEGRATION", "ukui-shell");
        isWayland = true;
    }

    kdk_dia_upload_program_startup();

    // locale
    _KYBi18nLoad("kylin-burner", "/usr/share/locale/");
    _KYBi18nDomain("kylin-burner");

    /* 适配4K屏以及分数缩放 */
    #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

    kdk::QtSingleApplication a(argc, argv);
    a.setWindowIcon(QIcon::fromTheme("burner"));
    a.setApplicationDisplayName(_("Burner"));

    //在程序启动时调用，不需要传入参数
    QCommandLineParser *parser;
    parser = new QCommandLineParser;
    parser->addPositionalArgument( "urls", _("file(s) to open"), "[urls...]" );
    parser->addOption(QCommandLineOption("d", _("Running as debug model.")));
    parser->process(a);
    if (parser->isSet("d"))
        Configuration::instance()->set("logger","level", 4);
    else
        Configuration::instance()->set("logger","level", 1);

    //check already running
    QDBusInterface interface("com.kylin.burner.manager",
                              "/com/kylin/burner/manager",
                              "com.kylin.burner.manager",
                              QDBusConnection::sessionBus());

    QDBusReply<int> reply = interface.call("slotsReShowMainWindow", parser->positionalArguments());
    if (reply.isValid()) {
        switch(reply.value()) {
        case 0:
            qDebug()<<"The kylin-burner process is running, 0 argument, active mainwindow";
            break;
        case 1:
            qDebug()<<"The kylin-burner process is running, 1 argumentactive mainwindow and swith burn image view";
            break;
        default:
            qDebug()<<"The kylin-burner process is running";
            break;
        }
        exit(0);
    }

#ifndef QT_NO_TRANSLATION
    // QT自身标准的翻译
    QString locale = QLocale::system().name();
    QString translatorFileName = QLatin1String("qt_");
    translatorFileName += locale;
    QTranslator *selfTransOfQt = new QTranslator();
    if (selfTransOfQt->load(translatorFileName, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        a.installTranslator(selfTransOfQt);
    else
        qDebug() << "load qt translator file failed!";
#endif

    // 加载sdk控件翻译
    QTranslator trans;
    if (locale == "zh_CN") {
        if (trans.load(":/translations/gui_zh_CN.qm")) {
            a.installTranslator(&trans);
        }
    } else if (locale == "bo_CN") {
        if (trans.load(":/translations/gui_bo_CN.qm")) {
            a.installTranslator(&trans);
        }
    } else if (locale == "mn_MN") {
        if (trans.load(":/translations/gui_mn.qm")) {
            a.installTranslator(&trans);
        }
    } else if (locale == "zh_HK") {
        if (trans.load(":/translations/gui_zh_HK.qm")) {
            a.installTranslator(&trans);
        }
    }

    //EverTime Burner Start, init [DataSetting]--Duplicate Data/Add Data/Delete Data/clean Data
    //it can reduce some error when user some operation
    Configuration::instance()->set("DataSetting", "Duplicate Data", 0);
    Configuration::instance()->set("DataSetting", "Add Data", false);
    Configuration::instance()->set("DataSetting", "Delete Data", false);
    Configuration::instance()->set("DataSetting", "Clean Data", true);

    Configuration::instance()->set("FilterFile","hidden",false);
    Configuration::instance()->set("FilterFile","broken",false);
    Configuration::instance()->set("FilterFile","Repleace",false);

    Utils::initSystemInfo();
    LOGGER->init();
    MenuFactory::instance()->init();
    TIP_BURNRESULT->init();
    ViewFilterFiles::instance()->init();
    MAIN->init();
    COPY_IMGAE->init();
    ExecDialog::instance()->init();

    MainWindow::Instance(parser->positionalArguments(), nullptr);
    kdk::UkuiStyleHelper::self()->removeHeader(MainWindow::Instance());
    a.setActivationWindow(MainWindow::Instance());
    MainWindow::Instance()->show();

    AboutDialog::instance(MainWindow::Instance());
    AboutDialog::instance()->init();
    kdk::WindowManager::setSkipSwitcher(AboutDialog::instance()->windowHandle(),true);

    MODAL->setAttribute(Qt::WA_NativeWindow);
    MODAL->windowHandle()->setTransientParent(MainWindow::Instance()->windowHandle());

    FileFilterRules::instance()->setAttribute(Qt::WA_NativeWindow);
    FileFilterRules::instance()->windowHandle()->setTransientParent(MainWindow::Instance()->windowHandle());

    EXEC->setAttribute(Qt::WA_NativeWindow);
    EXEC->windowHandle()->setTransientParent(MainWindow::Instance()->windowHandle());

    TIP_BURNRESULT->setAttribute(Qt::WA_NativeWindow);
    TIP_BURNRESULT->windowHandle()->setTransientParent(MainWindow::Instance()->windowHandle());

    ViewFilterFiles::instance()->setAttribute(Qt::WA_NativeWindow);
    ViewFilterFiles::instance()->windowHandle()->setTransientParent(MainWindow::Instance()->windowHandle());

    kdk::WindowManager::setGeometry(MainWindow::Instance()->windowHandle(),
                                    QRect(QPoint(qApp->desktop()->screenGeometry(MainWindow::Instance()).width()/2 - MainWindow::Instance()->width()/2,
                                          qApp->desktop()->screenGeometry(MainWindow::Instance()).height()/2 - MainWindow::Instance()->height()/2),
                                    QSize(MainWindow::Instance()->size())));

    LogicMain::instance()->initISO();

    return a.exec();
}
