#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include <QStandardPaths>
#include <QLibraryInfo>
#include <QDir>
#include <fcntl.h>
#include <syslog.h>
#include <QDebug>
#include <QFile>
#include <QMutex>
#include <QDateTime>
#include <sys/inotify.h>
#include <signal.h>

#include <singleapplication.h>
#include "log.hpp"
#include "windowmanage.hpp"

#include "controller/control.h"
#include "network/tcp_client.h"
#include "network/udp_socket.h"
#include "global/utils/global_data.h"
#include "global/declare/declare.h"
#include "view/kyview.h"
#include <kysdk/diagnosetest/libkydatacollect.h>

void pipeHandler(int)
{
    qDebug() << "Info : catch signal SIGPIPE !!!";
    return;
}

int catchSig()
{
    int ret = -1;

    struct sigaction action;
    memset(&action, 0x00, sizeof(struct sigaction));

    action.sa_handler = pipeHandler;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;

    ret = sigaction(SIGPIPE, &action, NULL);
    if (ret) {
        qDebug() << "Info : sigaction signal SIGPIPE fail!";
    }

    return 0;
}

int main(int argc, char *argv[])
{
    //在程序启动时调用，不需要传入参数
    kdk_dia_upload_program_startup();

    /* 使用sdk管理日志 */
    qInstallMessageHandler(::kabase::Log::logOutput);

    /* 适配4K屏以及分数缩放 */
    ::kabase::WindowManage::setScalingProperties();

    /* 获取命令行参数 */
    if (argc > 1) {
        QString argValueStr = argv[1];
        if (argValueStr == "-d" || argValueStr == "--debug") {
            GlobalUtils::DEBUG_MODE = true;
        }
    }

    qRegisterMetaType<ChatMsgInfo>("ChatMsgInfo");
    qRegisterMetaType<ChatMsgInfo>("ChatMsgInfo&");
    qRegisterMetaType<g_tcpItem>("g_tcpItem");

    kdk::QtSingleApplication app(argc, argv);
    app.setApplicationVersion("1.3.1");
    app.setWindowIcon(QIcon::fromTheme("kylin-ipmsg"));

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

    /* 设置不使用gtk3平台文件对话框 */
    app.setProperty("useFileDialog", false);

    /* 加载翻译文件 */
    QString kylinIpmsgTransPath = "/usr/share/kylin-ipmsg/data/translations";
    QString peonyTransPath = "/usr/share/libpeony-qt";
    QString qtTransPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    QString locale = QLocale::system().name();

    QTranslator trans_global, trans_peony, trans_qt;
    QTranslator trans_SDK;

    if (!trans_global.load(QLocale(), "kylin-ipmsg", "_", kylinIpmsgTransPath)) {
        qDebug() << "Load global translations file" << QLocale() << "failed!";
    } else {
        app.installTranslator(&trans_global);
    }

    if (!trans_peony.load(QLocale(), "libpeony-qt", "_", peonyTransPath)) {
        qDebug() << "Load libpeony translations file" << QLocale() << "failed!";
    } else {
        app.installTranslator(&trans_peony);
    }

    if (!trans_qt.load(QLocale(), "qt", "_", qtTransPath)) {
        qDebug() << "Load qt translations file" << QLocale() << "failed!";
    } else {
        app.installTranslator(&trans_qt);
    }
    
    if (locale == "zh_CN") {
        if (trans_SDK.load(":/translations/gui_zh_CN.qm")) {
            app.installTranslator(&trans_SDK);
        }
    }
    if (locale == "bo_CN") {
        if (trans_SDK.load(":/translations/gui_bo_CN.qm")) {
            app.installTranslator(&trans_SDK);
        }
    }
    /* 捕捉信号SIGPIPE */
    catchSig();

    /* 实例逻辑中心 */
    Control::getInstance();

    /* 移除标题栏 */
    ::kabase::WindowManage::removeHeader(KyView::getInstance());

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

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

    KyView::getInstance()->checkLocalName();

    return app.exec();
}
