/*
 * Copyright (C) 2022 Tianjin KYLIN Information Technology 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, 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 <http://www.gnu.org/licenses/>.
 *
**/
#include <QCoreApplication>
#include <QTimer>
#include <QFileInfo>
#include <QScreen>
#include <QDebug>
#include <QString>
#include <QFileInfo>
#include <QCursor>
#include <QPalette>
#include <QDesktopWidget>
#include <QApplication>
#include <QWidget>
#include <QGSettings/QGSettings>
#include <kysdk/kysdk-system/libkysysinfo.h>

extern "C" {
#include <X11/Xatom.h>
#include <X11/Xlib.h>
}


#define XSETTINGS_SCHEMA    "org.ukui.SettingsDaemon.plugins.xsettings"
#define MOUSE_SCHEMA        "org.ukui.peripherals-mouse"
#define SCALING_KEY         "scaling-factor"
#define CURSOR_SIZE         "cursor-size"
#define CURSOR_THEME        "cursor-theme"


/* 设置DPI环境变量 */
void setXresources(double scale)
{
    Display    *dpy;
    QGSettings *mouse_settings = new QGSettings(MOUSE_SCHEMA);
    QString str = QString("Xft.dpi:\t%1\nXcursor.size:\t%2\nXcursor.theme:\t%3\n")
                         .arg(scale * 96)
                         .arg(mouse_settings->get(CURSOR_SIZE).toInt() * scale)
                         .arg(mouse_settings->get(CURSOR_THEME).toString());

    dpy = XOpenDisplay(NULL);
    XChangeProperty(dpy, RootWindow(dpy, 0), XA_RESOURCE_MANAGER, XA_STRING, 8,
                    PropModeReplace, (unsigned char *) str.toLatin1().data(), str.length());
    XCloseDisplay(dpy);

    qDebug() << "setXresources：" << str;

    delete mouse_settings;
}

/* 过滤低分辨率高缩放比情况 */
void screenScaleJudgement(QGSettings *settings)
{
    qreal        scaling = qApp->devicePixelRatio();
    double       scale;
    scale = settings->get(SCALING_KEY).toDouble();
    if (scale > 1.25) {
        bool state  = false;
        bool mScale = false;

        for (QScreen *screen : QGuiApplication::screens()) {
            int width  = screen->geometry().width() * scaling;
            int height = screen->geometry().height() * scaling;

            if (width < 1920 && height < 1080) {
                state = true;
            }
            else if (width == 1920 && height == 1080 && scale > 1.5) {
                state = true;
            }
            /*
            else if (width > 2560 && height > 1440) {
                mScale = true;
            }
            */
        }

//        if (state && !mScale) {
        if (state) {
            settings->set(SCALING_KEY, 1.0);
            scale = 1.0;
        }
    }
    setXresources(scale);
}

/* 判断文件是否存在 */
bool isFileExist(QString XresourcesFile)
{
    QFileInfo fileInfo(XresourcesFile);
    if (fileInfo.isFile()) {
        qDebug() << "File exists";
        return true;
    }

    qDebug() << "File does not exis";

    return false;
}

/* 编写判断标志文件，更改 鼠标/DPI 配置大小*/
void writeXresourcesFile(QString XresourcesFile, QGSettings *settings, double scaling)
{
    QFile file(XresourcesFile);
    QString content = QString("Xft.dpi:%1\nXcursor.size:%2").arg(96.0 * scaling).arg(24.0 * scaling);
    QByteArray str = content.toLatin1().data();

    file.open(QIODevice::ReadWrite | QIODevice::Text);
    file.write(str);
    file.close();

    QGSettings *Font = new QGSettings("org.ukui.font-rendering");

    Font->set("dpi", 96.0);
    settings->set(SCALING_KEY, scaling);

    qDebug() << " writeXresourcesFile: content = " << content
             << " scalings = " << settings->get(SCALING_KEY).toDouble();
    delete Font;
}

/* 判断是否为首次登陆 */
bool isTheFirstLogin(QGSettings *settings)
{
    QString homePath       = getenv("HOME");
    QString XresourcesFile = homePath+"/.config/xresources";
    QString Xresources     = homePath+"/.Xresources";
    qreal   scaling        = qApp->devicePixelRatio();
    bool    zoom1 = false, zoom2 = false, zoom3 = false;
    double  mScaling;
    bool xres, Xres;

    Xres = isFileExist(Xresources);
    xres = isFileExist(XresourcesFile); //判断标志文件是否存在

    if (xres && !Xres) {
        return false;
    } else if (xres && Xres) {
        QFile::remove(Xresources);
        return false;
    } else if (Xres && !xres) {
        QFile::rename(Xresources, XresourcesFile);
        return false;
    }

    for (QScreen *screen : QGuiApplication::screens()) {
        int width  = screen->geometry().width() * scaling;
        int height = screen->geometry().height() * scaling;

        if (width <= 1920 && height <= 1080) {
            zoom1 = true;
        } else if (width > 1920 && height > 1080 && width <= 2560 && height <=1500) {
            zoom2 = true;
        } else if (width > 2560 && height > 1440) {
            zoom3 = true;
        }
    }

    if (zoom1) {
        mScaling = 1.0;
    } else if (!zoom1 && zoom2) {
        mScaling = 1.5; //考虑新版缩放，设置默认150%暂时停止设置；
    } else if (!zoom1 && !zoom2 && zoom3) {
        mScaling = 2.0;
    }

    writeXresourcesFile(XresourcesFile, settings, mScaling);

    setXresources(mScaling);

    return true;
}

/* 配置新装系统、新建用户第一次登陆时，4K缩放功能*/
void setHightResolutionScreenZoom(bool platForm)
{
    QGSettings *settings;
    double      scale;
    int         ScreenNum = QApplication::screens().length();
    if (!QGSettings::isSchemaInstalled(XSETTINGS_SCHEMA) || !QGSettings::isSchemaInstalled("org.ukui.font-rendering") ||
            !QGSettings::isSchemaInstalled(MOUSE_SCHEMA)) {
        qDebug() << "Error: ukui-settings-daemon's Schema  is not installed, will not setting dpi!";
        delete settings;
        return;
    }
    settings = new QGSettings(XSETTINGS_SCHEMA);

    scale = settings->get(SCALING_KEY).toDouble();

    if (platForm) {
        setXresources(scale);
        goto end;
    }

    if (isTheFirstLogin(settings)) {
        qDebug() << "Set the default zoom value when logging in for the first time.";
        goto end;
    }
    /* 过滤单双屏下小分辨率大缩放值 */


    if (ScreenNum > 1) {
        setXresources(scale);
        goto end;
    }

    screenScaleJudgement(settings);

end:
    delete settings;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QString platForm = kdk_system_get_hostCloudPlatform();
    if (platForm == "none") {
        qDebug() << "platForm=" << platForm << ", 系统环境为实体机";
        setHightResolutionScreenZoom(false);
    } else {
        qDebug() << "platForm=" << platForm << ", 系统环境为云环境";
        setHightResolutionScreenZoom(true);
    }
    return 0;
}
