/*
 * 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 "ctrl.h"

#include <QMetaType>
#include <QDBusMetaType>
#include <QCoreApplication>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QJsonParseError>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>
#include "usdbrightness.h"
#include <QString>
#include <QRegExp>
#include <QString>
#include <QDebug>
#include <QList>
#include <QFile>
#include <QTextStream>

#include <KF5/KScreen/kscreen/output.h>
#include <KF5/KScreen/kscreen/edid.h>
#include <KF5/KScreen/kscreen/mode.h>
#include <KF5/KScreen/kscreen/config.h>
#include <KF5/KScreen/kscreen/getconfigoperation.h>
#include <KF5/KScreen/kscreen/configmonitor.h>
#include <KF5/KScreen/kscreen/setconfigoperation.h>
#include <KF5/KScreen/kscreen/edid.h>
#include <KF5/KScreen/kscreen/types.h>

ctrl::ctrl() : QObject()
{
    if (QGSettings::isSchemaInstalled(QByteArray("org.ukui.control-center.panel.plugins"))) {
        QGSettings gsettings(QByteArray("org.ukui.control-center.panel.plugins"), QByteArray(), this);
//        gsettings.set("gammaforbrightness", true);
    }
    QObject::connect(new KScreen::GetConfigOperation(), &KScreen::GetConfigOperation::finished,
                     [&](KScreen::ConfigOperation *op) {
                         const KScreen::ConfigPtr config = qobject_cast<KScreen::GetConfigOperation *>(op)->config();
                         KScreen::ConfigMonitor::instance()->addConfig(config);
                         for (KScreen::OutputPtr output : config.data()->connectedOutputs()) {
                             qInfo() << "Starting config screen name: " << output->name();
                             m_screenNameList.append(output->name());
                         }
                     });
}

void ctrl::controlMprisPlayerDbus(const QString funcName)
{
    if (m_dbusMprisInterface == nullptr) {
        m_dbusMprisInterface = new QDBusInterface(SESSION_DBUS_NAME_STR_FIELD, SESSION_DBUS_PLAYER_PATH,
                                                  SESSION_DBUS_PLAYER_INTERFACE, QDBusConnection::sessionBus());
    }
    if (m_dbusMprisInterface->isValid()) {
        if (funcName.startsWith("seek")) {
            QStringList itemList = funcName.trimmed().split(':');
            bool ok;
            qlonglong value = itemList.value(1).toLongLong(&ok);
            if (ok) {
                m_dbusMprisInterface->asyncCall("operation", itemList.value(0), QVariantList() << value);
            }
            return;
        }
        if (funcName.startsWith("setRate")) {
            QStringList itemList = funcName.trimmed().split(':');
            bool ok;
            double value = itemList.value(1).toDouble(&ok);
            if (ok) {
                m_dbusMprisInterface->asyncCall("operation", itemList.value(0), QVariantList() << value);
            }
            return;
        }
        m_dbusMprisInterface->asyncCall("operation", funcName, QVariantList());
    }
}

void ctrl::setBrightness(bool isUp)
{
    if (m_dbusBrightnessInterface == nullptr) {
        m_dbusBrightnessInterface = new QDBusInterface(SESSION_DBUS_NAME_BRIGHTNESS, SESSION_DBUS_BRIGHTNESS_PATH,
                                                       SESSION_DBUS_BRIGHTNESS_INTERFACE, QDBusConnection::sessionBus());
    }
    QDBusMessage res =m_dbusBrightnessInterface->call("getPrimaryBrightness");
    int value = res.arguments().first().toUInt();
    qInfo() << "get screen brightness: " << value;
    if (isUp) {
        if (value >= 100) {
            value = 100;
        } else {
            value += 10;
        }
    } else {
        if (value <= 0) {
            value = 0;
        } else {
            value -= 10;
        }
    }
    qInfo() << "set screen brightness: " << value;
    res = m_dbusBrightnessInterface->call("setPrimaryBrightness", (quint32)value);
}

void ctrl::setDefaultAdapterSwitchStatus(bool power)
{
    QDBusInterface * dbusMsg = new QDBusInterface(SYSTEM_DBUS_BLE_SERVICE, SYSTEM_DBUS_BLE_PATH,
                                              SYSTEM_DBUS_BLE_INTERFACE, QDBusConnection::sessionBus());
    QDBusMessage response = dbusMsg->call("setDefaultAdapterPower",power);

    if (response.type() == QDBusMessage::ReplyMessage) {
        qInfo() << "set Ble status:" << response.arguments().takeFirst().toBool();
    }
}
