#include "msgpane.h"
#include "cmainwnd.h"
#include "global/kaglobal.h"

#include <QApplication>
#include <QFileInfo>
#include <QDir>
#include <QTranslator>
#include <QLibraryInfo>
//窗口显示在屏幕中心
#include <QWidget>
#include <QCommandLineParser>
#include <QScreen>
#include <QDir>

#include <kysdk/applications/kabase/single_application/single_application.hpp>
#include <windowmanager/windowmanager.h>

QStringList translationsPaths() {
    QString binaryPath = QFileInfo(qApp->applicationDirPath())
            .absoluteFilePath();

    QString trPath = QDir::toNativeSeparators(binaryPath + "/translations") ;
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
    return QStringList()
            << QStringLiteral(APP_PREFIX) + "/share/kylin-aiassistant/translations"
            << trPath
            << QStringLiteral("/usr/share/kylin-aiassistant/translations")
            << QStringLiteral("/usr/local/share/kylin-aiassistant/translations");
#elif defined(Q_OS_WIN)
    return QStringList()
            << trPath;
#endif
}

static void initDataDir()
{
    // 获取用户家目录下的文档目录路径
    QString documentsDir = QDir::homePath() + "/文档";
    // 创建新的文件夹路径
    QString dataDirPath = documentsDir + "/kylin-aiassistant";

    QDir dataDir(dataDirPath);
    if(!dataDir.exists()) {
       dataDir.mkdir(dataDirPath);
    }

    QString dialogPath = dataDirPath + "/dialog";

    QDir dialogPathDir(dialogPath);
    if(!dialogPathDir.exists()) {
       dialogPathDir.mkdir(dialogPath);
    }

    QString fileName = "message.json";
    QString filePath = dialogPath + "/" + fileName;
    QFile file(filePath);

    if (!file.exists()) {
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream stream(&file);
            stream << "[]";
            file.close();
        } else {
            qDebug() << "无法创建文件：" << filePath;
            return;
        }
    }

    dialogPath = dataDirPath + "/meeting";

    QDir dialogPathDir1(dialogPath);
    if(!dialogPathDir1.exists()) {
       dialogPathDir1.mkdir(dialogPath);
    }

    return;
}

using namespace kdk::kabase;

int main(int argc, char *argv[])
{
    // 修改分辨率的显示
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
        QtSingleApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
        QtSingleApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
    #endif

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

    // arm架构应用会阻止重启
    qunsetenv("SESSION_MANAGER");

    QtSingleApplication app(argc, argv);
    // 发言人重命名后报错 QQuickWidget cannot be used as a native child widget. Consider setting Qt::AA_DontCreateNativeWidgetSiblings
    app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);

    QCommandLineParser parser;
    parser.setApplicationDescription("kylin-aiassistant");
    parser.addHelpOption();

    QCommandLineOption silenceOption(QStringList() << "s" << "silence",
            QCoreApplication::translate("main", "Start silently."));
    parser.addOption(silenceOption);

    parser.process(app);

    const QStringList args = parser.positionalArguments();

    bool silence = parser.isSet(silenceOption);

    if (app.isRunning()) {
        if (!silence) {
            // 非首次启动行为为激活AI助手，弹出AI助手的UI界面
            app.sendMessage("running , 4000");
        }
        return 0;
    }

    QTranslator translator, qtTranslator;
    QStringList trPaths = translationsPaths();

    for (const QString &path: trPaths) {
        qDebug() << "binaryPath" << path;
        bool match = translator.load(QLocale(),
                                     QStringLiteral("Internationalization"), QStringLiteral(
                                         "_"),
                                     path);
        if (match) {
            break;
        }
    }

    qtTranslator.load(QLocale::system(), "qt", "_",
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));

    // sdk翻译加载
    QTranslator sdkTrans;
    sdkTrans.load(":/translations/gui_"+QLocale::system().name()+".qm");

    app.installTranslator(&translator);
    app.installTranslator(&qtTranslator);
    app.installTranslator(&sdkTrans);

    initDataDir();

    app.setApplicationName(QObject::tr("kylin-aiassistant"));

    CMainWnd wnd;

    // 需要设置焦点窗口，这样再次启动的时候激活该窗口
    app.setActivationWindow(&wnd);

    // 非首次启动行为为激活AI助手，弹出AI助手的UI界面
    QObject::connect(&app, SIGNAL(messageReceived(const QString&)), &wnd, SLOT(onAppRestarted()));

    if (!silence) {
        wnd.show();

        if(! g_gsettings->get("is-nlp-setup").toBool() && !g_gsettings->get("is-vision-setup").toBool()){
            wnd.onConfActionTriggered();
        }
    }

    return app.exec();
}
