/*
 * Copyright (C) 2022, 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/>.
 *
 * Authors: iaom <zhangpengfei@kylinos.cn>
 *
 */
#include "brightness-shortcut.h"
#include "dbus-connector.h"

#include <QDebug>
#include <QTranslator>
#include <QApplication>
#include <QDBusReply>
#include <QDBusInterface>
#include <QtMath>

#define UKUI_SETTINGS_DAEMON_NAME                    "org.ukui.SettingsDaemon"
#define UKUI_GLOBAL_BRIGHTNESS_PATH                  "/GlobalBrightness"
#define UKUI_SETTINGS_DAEMON_BRIGHTNESS_INTERFACE    "org.ukui.SettingsDaemon.Brightness"

using namespace UkuiShortcut;
using namespace UkuiQuick;

BrightnessShortcut::BrightnessShortcut(QObject *parent) : Shortcut(parent)
{
    m_currentStatusInfo.setValue(0);
    m_currentStatusInfo.setIcon("ukui-light-0-symbolic");
    m_currentStatusInfo.setToolTip(tr("Brightness"));
    initMetaData();

    DbusConnector* dbusConnector = new DbusConnector(UKUI_SETTINGS_DAEMON_NAME,
                                                     UKUI_GLOBAL_BRIGHTNESS_PATH,
                                                     UKUI_SETTINGS_DAEMON_BRIGHTNESS_INTERFACE,
                                                     QDBusConnection::sessionBus());
    connect(dbusConnector, &DbusConnector::ready, this, &BrightnessShortcut::onDbusConnectorReady);
    dbusConnector->start();
}

BrightnessShortcut::~BrightnessShortcut() = default;

QString BrightnessShortcut::pluginId()
{
    return QStringLiteral("BrightnessShortcut");
}

void BrightnessShortcut::active(PluginMetaType::Action action)
{
    Q_UNUSED(action);
}

void BrightnessShortcut::setValue(int value)
{
    if (m_isEnable) {
        if (m_interface && m_interface->isValid()) {
            if (m_enhance) {
                if (m_enhancedBrightness == value) return;
                value = qFloor((double)value * (150.0 / 100.0));
                m_enhancedBrightness = qFloor(value * (100.0 / 150.0));
            }
            m_interface->asyncCall("setPrimaryBrightness", static_cast<quint32>(value));
        }
    }
}

const StatusInfo BrightnessShortcut::currentStatus()
{
    return m_currentStatusInfo;
}

bool BrightnessShortcut::isEnable()
{
    return m_isEnable;
}

void BrightnessShortcut::changeValue(quint32 brightness)
{
    if(m_currentBrightness == brightness) {
        return;
    }
    m_currentBrightness = brightness;

    if (m_enhance) {
        brightness *= (100.0 / 150.0);
    }

    updateStatusInfo(qFloor(brightness));
}

void BrightnessShortcut::updateStatusInfo(quint32 brightness)
{
    if(brightness <= 100) {
        if(brightness == 0) {
            m_currentStatusInfo.setIcon("ukui-light-0-symbolic");
        } else if (brightness <= 25) {
            m_currentStatusInfo.setIcon("ukui-light-25-symbolic");
        } else if (brightness <= 50) {
            m_currentStatusInfo.setIcon("ukui-light-50-symbolic");
        } else if (brightness <= 75) {
            m_currentStatusInfo.setIcon("ukui-light-75-symbolic");
        } else {
            m_currentStatusInfo.setIcon("ukui-light-100-symbolic");
        }
        if (m_enhance) {
            if (brightness == m_enhancedBrightness) {
                Q_EMIT statusChanged(m_currentStatusInfo);
                return;
            }
            m_enhancedBrightness = brightness;
        }
        m_currentStatusInfo.setValue(static_cast<int>(brightness));

    } else {
        qWarning() << "Brightness value error: " << brightness;
        m_currentStatusInfo.setDisable(true);
        m_currentStatusInfo.setValue(0);
        m_currentStatusInfo.setIcon("ukui-light-0-symbolic");
    }

    Q_EMIT statusChanged(m_currentStatusInfo);
}

QMap<PluginMetaType::SystemMode, PluginMetaData> BrightnessShortcut::pluginMetaData()
{
    return m_metaData;
}

void BrightnessShortcut::initMetaData()
{
    PluginMetaData pc {true, 0, PluginMetaType::PluginType::ProgressBar};
    PluginMetaData tablet {true, 0, PluginMetaType::PluginType::ProgressBar};
    m_metaData.insert(PluginMetaType::SystemMode::PC, pc);
    m_metaData.insert(PluginMetaType::SystemMode::Tablet, tablet);
}

void BrightnessShortcut::onDbusConnectorReady(QDBusInterface *interface)
{
    if (!interface || !interface->isValid()) return;
    m_interface = interface;

    QDBusReply<bool> isEnable = m_interface->call("isEnable");
    if (isEnable.isValid()) {
        m_isEnable = isEnable.value();
        onEnableChanged(m_isEnable);
    }

    QDBusReply<bool> enhance = m_interface->call("isEnhancementBrightness");
    if (enhance.isValid()) {
        m_enhance = enhance.value();
    }

    QDBusReply<quint32> v = m_interface->call("getPrimaryBrightness");
    changeValue(v.isValid() ? v.value() : 0);

    if (!QDBusConnection::sessionBus().connect(UKUI_SETTINGS_DAEMON_NAME,
                                               UKUI_GLOBAL_BRIGHTNESS_PATH,
                                               UKUI_SETTINGS_DAEMON_BRIGHTNESS_INTERFACE, "enableChanged", this, SLOT(onEnableChanged(bool)))) {
        qDebug() << "BrightnessShortcut: QDBusConnection::sessionBus() connect enableChanged failed";
    }

    if (!QDBusConnection::sessionBus().connect(UKUI_SETTINGS_DAEMON_NAME,
                                               UKUI_GLOBAL_BRIGHTNESS_PATH,
                                               UKUI_SETTINGS_DAEMON_BRIGHTNESS_INTERFACE, "primaryBrightnessChangedEnd", this, SLOT(changeValue(quint32)))) {
        qDebug() << "BrightnessShortcut: QDBusConnection::sessionBus() connect primaryBrightnessChangedEnd failed";
    }

    if (!QDBusConnection::sessionBus().connect(UKUI_SETTINGS_DAEMON_NAME,
                                               UKUI_GLOBAL_BRIGHTNESS_PATH,
                                               UKUI_SETTINGS_DAEMON_BRIGHTNESS_INTERFACE, "enhancementBrightnessSwitchChanged", this, SLOT(onEnhanceChanged(bool)))) {
        qDebug() << "BrightnessShortcut: QDBusConnection::sessionBus() connect enhancementBrightnessSwitchChanged failed";
    }
}

void BrightnessShortcut::onEnableChanged(bool enable)
{
    if (m_isEnable == enable) {
        return;
    }

    m_isEnable = enable;
    if (m_isEnable) {
        QDBusReply<quint32> v = m_interface->call("getPrimaryBrightness");
        changeValue(v.isValid() ? v.value() : 0);
    }

    Q_EMIT enableStatusChanged(m_isEnable);
}

void BrightnessShortcut::onEnhanceChanged(bool enhance)
{
    if (enhance != m_enhance) {
        m_enhance = enhance;
        changeValue(m_currentBrightness);
    }
}

BrightnessShortcutPlugin::BrightnessShortcutPlugin(QObject *parent) : UkuiShortcutPlugin(parent)
{

}

QStringList BrightnessShortcutPlugin::translations()
{
    return {QStringLiteral("brightness-shortcut")};
}

Shortcut *BrightnessShortcutPlugin::createShortcut()
{
    return new BrightnessShortcut;
}
