#include "controller/core/viewcontrol.h"
#include <QApplication>
#include <QObject>
#include <signal.h>
#include <QDBusInterface>
#include <single_application/single_application.hpp>
#include <window_management.hpp>
#include "kabaselog.hpp"
#include "windowmanage.hpp"

//初始化核心，初始化前端，启动时是否展示界面
void controlView(kdk::kabase::QtSingleApplication &a, const QStringList &args, bool isStart)
{
    //实例化viewcontrol

    viewControl::getInstance()->initCore(args, isStart);
    QObject::connect(&a, &kdk::kabase::QtSingleApplication::messageReceived, viewControl::getInstance(),
                     &viewControl::toShowView);
    //激活窗口
    ::kabase::WindowManage::removeHeader(viewControl::getInstance()->activeWindow());
    a.setActivationWindow(viewControl::getInstance()->activeWindow());
}
int main(int argc, char *argv[])
{
    //适配4K屏以及分数缩放
    kdk::kabase::WindowManagement::setScalingProperties();
    //日志输出
    qInstallMessageHandler(::kabase::KabaseLog::logOutput);
    kdk::kabase::QtSingleApplication a(argc, argv);

    a.setWindowIcon(QIcon::fromTheme("kylin-weather"));
    //单例
    if (a.isRunning()) {
        qDebug() << "is running";
        a.sendMessage("running , 4000");
        return 0;
    }
    //翻译
    QTranslator qt_trans;
    QString locale = QLocale::system().name();
    QString trans_path;
    if (QDir("/usr/share/kylin-weather/translations").exists()) {
        trans_path = "/usr/share/kylin-weather/translations";
    } else {
        trans_path = qApp->applicationDirPath() + "/translations";
    }
    QString qt_trans_path;
    qt_trans_path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); // /usr/share/qt5/translations
    if (!qt_trans.load("qt_" + locale + ".qm", qt_trans_path)) {
        qDebug() << "Load translation file："
                 << "qt_" + locale + ".qm from" << qt_trans_path << "failed!";
    } else {
        a.installTranslator(&qt_trans);
    }
    QTranslator sdk_trans;
    if (sdk_trans.load(":/translations/gui_" + locale + ".qm")) {
        a.installTranslator(&sdk_trans);
    }
    QTranslator app_trans;
    if (!app_trans.load("kylin-weather_" + locale + ".qm", trans_path)) {
        qDebug() << "Load translation file："
                 << "kylin-weather_" + locale + ".qm from" << trans_path << "failed!";
    } else {
        a.installTranslator(&app_trans);
    }
    a.setApplicationName(QApplication::tr("Weather"));
    //初始化后端前端，判断启动方式，是否带参
    controlView(a, a.arguments(), !(argc == 2 && QLatin1String(argv[1]) == "showmainwindow"));

    return a.exec();
}
