#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>
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"


/* 过滤低分辨率高缩放比情况 */
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) {
            QGSettings *mGsettings = new QGSettings(MOUSE_SCHEMA);
            mGsettings->set(CURSOR_SIZE, 24);
            settings->set(SCALING_KEY, 1.0);
            delete mGsettings;
        }
    }
}

/* 设置DPI环境变量 */
void setXresources(int dpi)
{
    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(dpi)
                         .arg(mouse_settings->get(CURSOR_SIZE).toInt())
                         .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;
}

/* 判断文件是否存在 */
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");
    QGSettings *mouse_settings = new QGSettings(MOUSE_SCHEMA);

    Font->set("dpi", 96.0);
    settings->set(SCALING_KEY, scaling);
    mouse_settings->set(CURSOR_SIZE, scaling * 24.0);

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

/* 判断是否为首次登陆 */

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;
    } else if (!zoom1 && !zoom2 && zoom3) {
        mScaling = 2.0;
    }

    writeXresourcesFile(XresourcesFile, settings, mScaling);

    return true;
}


/* 配置新装系统、新建用户第一次登陆时，4K缩放功能*/
void setHightResolutionScreenZoom()
{
    QGSettings *settings;
    double      dpi;
    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);

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

    if (ScreenNum > 1) {
        goto end;
    }

    screenScaleJudgement(settings);

end:
    dpi = 0.0;
    dpi = settings->get(SCALING_KEY).toDouble() * 96.0;
    setXresources(dpi);
    delete settings;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    setHightResolutionScreenZoom();
    return 0;
}
