/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#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 <QQmlApplicationEngine>
#include <QSqlDatabase>
#include <QSqlError>
#include <QStandardPaths>
#include <QtQml>
#include <QSessionManager>
#include <QtQuickControls2/QtQuickControls2>

#include <windowmanager/windowmanager.h>
#include <kylin-ai/common/common.h>
#include <aiservicedialog.h>
#include <singleapplication.h>

const QString CONFIGPATH = "/.config/kylin-aiassistant/kylin-aiassistant.conf";

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 confFile = QDir::homePath() + CONFIGPATH;
    QSettings settings(confFile, QSettings::IniFormat);

    QString storedDirPath = settings.value("directories/baseDir", "").toString();

    QString dirPath;
    if (storedDirPath.isEmpty()) {
        // 使用默认路径
        QString docPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
        dirPath = docPath + "/kylin-aiassistant";

        settings.setValue("directories/baseDir", dirPath);
        KyInfo() << "使用默认路径" << dirPath;
    } else {
        // 使用存储的路径
        dirPath = storedDirPath;
        KyInfo() << "使用存储的路径" << dirPath;
    }

    QDir dir;
    if (!dir.exists(dirPath)) {
        if (!dir.mkpath(dirPath)) {
            KyInfo() << "创建助手目录失败";
            return;
        } else {
            KyInfo() << "创建助手目录成功 dirPath === " << dirPath;
        }
    }
    globals::defaultPath = dirPath;


    QString readPath = dirPath + "/.read";
    if (!dir.exists(readPath)) {
        if (!dir.mkpath(readPath)) {
            KyInfo() << "创建朗读目录失败";
            return;
        } else {
            KyInfo() << "创建朗读目录成功 dirPath === " << readPath;
        }
    }

    KyInfo() << "所有文件和目录初始化成功";
    return;
}

int main(int argc, char *argv[])
{
#ifndef QT_DEBUG
    initUkuiLog4qt("kylin-aiassistant");
#endif
    //wayland适配
    QString env = qgetenv("XDG_SESSION_TYPE");
    if(env == "wayland"){
        isWayland = true;

    }

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    QtSingleApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
    //暂时不使用主题的文件选择框，主题解决添加图片对话区域消失问题解决后，删除该选项
    //有些镜像使用主题的文件选择框会导致AI助手崩溃，具体的版本未知。
//    QtSingleApplication::setAttribute(Qt::AA_DontUseNativeDialogs);

    // 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."));
    QCommandLineOption selectedOption(QStringList() << "l" << "selected",
            QCoreApplication::translate("main", "Start with selected words."));
    QCommandLineOption fileOption(QStringList() << "f" << "file",
                QCoreApplication::translate("main", "Start with send file."));

    parser.addOption(silenceOption);
    parser.addOption(selectedOption);
    parser.addOption(fileOption);


    parser.process(app);

    const QStringList args = parser.positionalArguments();

    bool silence = parser.isSet(silenceOption);
    bool selected = parser.isSet(selectedOption);
    bool isFile = parser.isSet(fileOption);

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

        return 0;
    }

    /* 加载翻译文件 */
    QString kylinAiAssistantTransPath = "/usr/share/kylin-aiassistant/translations";
    QString qtTransPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
    QString locale = QLocale::system().name();

    KyInfo()<<"kylinAiAssistantTransPath"<<kylinAiAssistantTransPath;
    KyInfo()<<"qtTransPath"<<qtTransPath;
    KyInfo()<<"locale"<<locale;

    QTranslator trans_global , trans_qt;
    QTranslator trans_SDK;

    if (!trans_global.load(QLocale(), "Internationalization", "_", kylinAiAssistantTransPath)) {
        KyInfo() << "Load global translations file" <<QLocale() << "failed!";
    } else {
        app.installTranslator(&trans_global);
        KyInfo()<<"success!";
    }

    if (!trans_qt.load(QLocale(), "qt", "_", qtTransPath)) {
        KyInfo() << "Load qt translations file" <<QLocale() << "failed!";
    } else {
        app.installTranslator(&trans_qt);
    }

    QString path = QString(":/translations/gui_%1.qm").arg(locale);
    if (trans_SDK.load(path)) {
        app.installTranslator(&trans_SDK);
    }

    initDataDir();

    app.setApplicationName("kylin-aiassistant");

    if(!is_ai_subsystem_inited()){
       AiServiceDialog dialog;
       dialog.exec();
       return 0;
    }
    KyInfo()<<"子系统是否安装:"<<is_ai_subsystem_inited();

    CMainWnd wnd;
    // QtSingleApplication::setFallbackSessionManagementEnabled(false);
    //QObject::connect(&app,&QtSingleApplication::commitDataRequest,&wnd,&CMainWnd::commitData);
    // 需要设置焦点窗口，这样再次启动的时候激活该窗口
    app.setActivationWindow(&wnd);

    // 非首次启动行为为激活AI助手，弹出AI助手的UI界面
    QObject::connect(&app, &QtSingleApplication::messageReceived, &wnd, &CMainWnd::onAppRestarted);
    //设置跳过任务栏
   // kdk::WindowManager::setSkipTaskBar(wnd.windowHandle(),true);
    //设置跳过多任务视图
    //kdk::WindowManager::setSkipSwitcher(wnd.windowHandle(),true);


    if (!silence) {
        wnd.show();
        if(g_configManager->getConfigValue("is-first-install").toBool() == true){
            g_configManager->updateConfig("is-first-install", false);
            wnd.m_introductionView->m_isClosed = false;
            wnd.m_introductionView->showView();
        }else{
            wnd.m_introductionView->m_isClosed = true;
        }
    }

    //如果AI助手未启动，收到右键发送的文件，在这里处理
    if (isFile) {
        wnd.onAppRestarted(args.first());
    }

    return app.exec();
}
