/*
 * Kylin-video
 *
 * Copyright (C) 2021, 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 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/>.
 *
 * Authors: Liu Cong <liucong1@kylinos.cn>
 *
 */

#include "setupdialog.h"
#include "ui_setupdialog.h"
#include <KF5/KWindowSystem/kwindoweffects.h>

#include <QDebug>
#include <QGSettings>
#include <QMouseEvent>
#include <QListWidgetItem>

#include "global/xatom-helper.h"
#include "global/globalsignal.h"
#include "global/global.h"

using namespace Global;

SetUpDialog::SetUpDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SetUpDialog)
{
    ui->setupUi(this);
    initListWidget();
    initStyle();

    // 根据主题设置样式
    if(g_settings->value("General/follow_system_theme").toBool())
    {
        if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
            slotChangeTheme(false);
        else
            slotChangeTheme(true);
    }
    else
    {
        if(g_settings->value("General/theme").toInt() == 0)
            slotChangeTheme(false);
        else
            slotChangeTheme(true);
    }
    initConnect();
    if(isWayland)
        installEventFilter(this);
    else
        setModal(true);

}

SetUpDialog::~SetUpDialog()
{
    delete ui;
}

void SetUpDialog::setIndex(int index)
{
    ui->listWidget->setCurrentRow(index);
}

/** **********************************************
 * 主题颜色修改
 * 说明：所有需要根据主题修改颜色的控件都在此函数设置样式
 * @param: is_black_theme 是否为黑色主题
 *************************************************/
void SetUpDialog::slotChangeTheme(bool is_black_theme)
{
    if(is_black_theme)
    {
        ui->page_system->setBlackTheme();
        ui->page_play->setBlackTheme();
        ui->page_screenshot->setBlackTheme();
        ui->page_subtitle->setBlackTheme();
        ui->page_volume->setBlackTheme();
        ui->page_codec->setBlackTheme();
        ui->page_shortcut->setBlackTheme();

        ui->left->setStyleSheet("background-color:rgba(19,19,20,191)");
        ui->right->setStyleSheet("#right{background-color:rgb(38,38,38);}");
        ui->lab_name->setStyleSheet("color:rgb(255,255,255);");
        // 设置左侧list字体颜色
        for(int i=0; i<ui->listWidget->count(); i++)
        {
            QListWidgetItem *it = ui->listWidget->item(i);
            it->setTextAlignment(Qt::AlignCenter);
            it->setSizeHint(QSize(116, 32));
            it->setTextColor(QColor(249,249,249));
        }
        ui->btn_cancel->setStyleSheet("QPushButton{background-color:rgb(64,64,64);color:rgb(255,255,255);}"
                                      /*"QPushButton:hover{background-color:rgb(80,80,80);}"
                                      "QPushButton:pressed{background-color:rgb(50,50,50);}"*/);
        ui->btn_ok->setStyleSheet("QPushButton{background-color:rgb(55,144,250);color:rgb(255,255,255);}"
                                  /*"QPushButton:hover{background-color:rgb(80,80,80);}"
                                  "QPushButton:pressed{background-color:rgb(50,50,50);}"*/);
    }
    else
    {
        ui->page_system->setLightTheme();
        ui->page_play->setLightTheme();
        ui->page_screenshot->setLightTheme();
        ui->page_subtitle->setLightTheme();
        ui->page_volume->setLightTheme();
        ui->page_codec->setLightTheme();
        ui->page_shortcut->setLightTheme();

        ui->left->setStyleSheet("background-color:rgba(249,249,249,191)");
        ui->right->setStyleSheet("#right{background-color:#f9f9f9;}");
        ui->lab_name->setStyleSheet("color:rgb(48,49,51);");

//        QFont f("Noto Sans CJK SC Regular");
//        f.setPixelSize(16);
//        ui->listWidget->setFont(f);
        // 设置左侧list字体颜色
        for(int i=0; i<ui->listWidget->count(); i++)
        {
            QListWidgetItem *it = ui->listWidget->item(i);
            it->setTextAlignment(Qt::AlignCenter);
            it->setSizeHint(QSize(116, 32));
            it->setTextColor(QColor(89,89,89));
        }
        ui->btn_cancel->setStyleSheet("QPushButton{background-color:rgb(224,224,224);color:rgb(38,38,38);}"
                                      /*"QPushButton:hover{background-color:rgb(80,80,80);}"
                                      "QPushButton:pressed{background-color:rgb(50,50,50);}"*/);
        ui->btn_ok->setStyleSheet("QPushButton{background-color:rgb(55,144,250);color:rgb(255,255,255);}"
                                  /*"QPushButton:hover{background-color:rgb(80,80,80);}"
                                  "QPushButton:pressed{background-color:rgb(50,50,50);}"*/);
    }
}

void SetUpDialog::showEvent(QShowEvent *e)
{
    ui->page_system->initData();
    ui->page_play->initData();
    ui->page_screenshot->initData();
    ui->page_subtitle->initData();
    ui->page_volume->initData();

    resize(620, 400);
    // 设置模糊
    KWindowEffects::enableBlurBehind(winId(), true);
    gshortCut->makeAllInvalid();
    resetFont();
}

void SetUpDialog::hideEvent(QHideEvent *e)
{
    gshortCut->makeAllValid();
}

bool SetUpDialog::eventFilter(QObject *watched, QEvent *event)
{
    if(isWayland)
    {
        if(watched == this)
        {
            if (event->type() == QEvent::MouseButtonPress){
                auto mouseEvent = static_cast<QMouseEvent *>(event);
                if (mouseEvent->buttons() & Qt::LeftButton) {
                    UKUIDecorationManager::getInstance()->moveWindow(this->windowHandle());
                }
            }
        }
    }
    return false;
}

void SetUpDialog::initStyle()
{
    setFixedSize(620, 400);
    setAttribute(Qt::WA_TranslucentBackground);

    // 标题
    setWindowTitle(tr("Video Player Set up"));

    // 左侧列表
    ui->listWidget->setFixedWidth(140);
    ui->listWidget->setStyleSheet("QListWidget{background-color:rgba(19,19,20,0);padding:0px 5px;}"
                                  "QListWidget::Item:selected{width:116px;border-radius:6px;color:rgb(255,255,255);background-color:rgb(55,144,250);}");
    ui->listWidget->setSpacing(2);
    // 设置默认选中左侧列表中第一个
    ui->listWidget->setCurrentRow(0);
    ui->stackedWidget->setCurrentIndex(0);

    ui->btn_cancel->setFixedSize(80, 32);
    ui->btn_ok->setFixedSize(80, 32);

    ui->widget->setAttribute(Qt::WA_TranslucentBackground);
    ui->lab_name->setAttribute(Qt::WA_TranslucentBackground);

    ui->btn_icon->setFixedSize(QSize(26,26));
    ui->btn_icon->setIconSize(QSize(26,26));
    ui->btn_icon->setIcon(QIcon::fromTheme("kylin-video"));
    ui->btn_icon->setStyleSheet("QPushButton{border:0px;background:transparent;}"
                                "QPushButton::hover{border:0px;background:transparent;}"
                                "QPushButton::pressed{border:0px;background:transparent;}");

    QFont f("Noto Sans CJK SC Regular");
    f.setPixelSize(16);
    ui->lab_name->setFont(f);
    ui->lab_name->setText(tr("Setup"));

    ui->btn_close->setFixedSize(30, 30);
    ui->btn_close->setProperty("isWindowButton", 0x2);
    ui->btn_close->setProperty("useIconHighlightEffect", 0x8);
    ui->btn_close->setFlat(true);
    ui->btn_close->setIcon(QIcon::fromTheme("window-close-symbolic"));

    connect(ui->btn_close, &QPushButton::clicked, [&](){accept();});

    // 添加窗管协议
    if(!isWayland)
    {
        MotifWmHints hints;
        hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
        hints.functions = MWM_FUNC_ALL;
        hints.decorations = MWM_DECOR_BORDER;
        XAtomHelper::getInstance()->setWindowMotifHint(winId(), hints);
    }

    resetFont();
}

/** **********************************************
 * 初始化左侧列表
 *************************************************/
void SetUpDialog::initListWidget()
{
    ui->listWidget->addItem(tr("System"));
    ui->listWidget->addItem(tr("Play"));
    ui->listWidget->addItem(tr("ScreenShot"));
    ui->listWidget->addItem(tr("Subtitle"));
    ui->listWidget->addItem(tr("Audio"));
    ui->listWidget->addItem(tr("Codec"));     // 当前解码器选择功能先不做实现
    ui->listWidget->addItem(tr("Shortcut"));
}

void SetUpDialog::initConnect()
{
    // 主题改变
    connect(g_user_signal, &GlobalUserSignal::sigTheme, this, [&](int theme){
        switch (theme) {
        case 0:
            if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
                slotChangeTheme(false);
            else
                slotChangeTheme(true);
            break;
        case 1:
            slotChangeTheme(false);
            break;
        case 2:
            slotChangeTheme(true);
            break;
        default:
            break;
        }
    });

    connect(g_gsettings, &QGSettings::changed, this, [&](QString key){
        // 如果不是跟随主题的话直接返回,0是跟随主题
        if (key == "styleName") {
            if(g_settings->value("General/follow_system_theme").toInt())
            {
                if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
                    slotChangeTheme(false);
                else
                    slotChangeTheme(true);
            }
        }

        // 字体大小改变
        if (key == "systemFontSize" || key == "systemFont") {
            resetFont();
        }
    });

    connect(ui->listWidget, &QListWidget::currentRowChanged, [&](int index){ui->stackedWidget->setCurrentIndex(index);});
    connect(ui->btn_cancel, &QPushButton::clicked, [&](){ui->page_shortcut->clearChange();gsetup->clearChange();accept();});
    connect(ui->btn_ok, &QPushButton::clicked, [&](){ui->page_shortcut->flushChange();gsetup->flushChange();accept();});
}

void SetUpDialog::resetFont()
{
    QString fontFamily = g_gsettings->get("systemFont").toString();
    int fontSize = g_gsettings->get("systemFontSize").toInt();

    ui->page_system->setWidgetFont(fontFamily, fontSize);
    ui->page_codec->setWidgetFont(fontFamily, fontSize);
    ui->page_play->setWidgetFont(fontFamily, fontSize);
    ui->page_subtitle->setWidgetFont(fontFamily, fontSize);
    ui->page_shortcut->setWidgetFont(fontFamily, fontSize);
    ui->page_volume->setWidgetFont(fontFamily, fontSize);
    ui->page_screenshot->setWidgetFont(fontFamily, fontSize);

    QFont f(fontFamily);
    f.setPointSize(fontSize);
    ui->listWidget->setFont(f);

    f.setPointSize(fontSize + 2);
    ui->lab_name->setFont(f);
}
