/*
 * Copyright 2021 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 <http://www.gnu.org/licenses/>.
 */

#include "acwatcher.h"

#include <ksoundeffects.h>
using namespace kdk;

AcWatcher::AcWatcher():mOnBattery(false)
{

}


void AcWatcher::initAcWatcher()
{
    if (isSupportBattery()) {
        QDBusConnection::systemBus().connect(
                    UPOWER_SERVICE, UPOWER_PATH, FREEDESKTOP_UPOWER, "PropertiesChanged", this, SLOT(dealAcWatcherMssage(void)));
        mOnBattery = readOnBattery();
    }
}

void AcWatcher::dealAcWatcherMssage()
{
    bool value;
    value = readOnBattery();
    if (mOnBattery != value) {
        mOnBattery = value;
        emit acChanged(mOnBattery);
        qDebug() << "Power status change signal transmission";

        if (false == mOnBattery) {
            KSoundEffects::playSound(POWER_PLUG);
        }
    }
}

bool AcWatcher::readOnBattery()
{
    QDBusInterface iface(UPOWER_SERVICE, UPOWER_PATH, FREEDESKTOP_UPOWER, QDBusConnection::systemBus());
    QDBusReply<QVariant> reply = iface.call("Get", "org.freedesktop.UPower", "OnBattery");
    if (reply.isValid()) {
        return reply.value().toBool();
    }
    qDebug() << "OnBattery error!";
    return false;
}

bool AcWatcher::isSupportBattery()
{
    QFile file("/sys/class/dmi/id/chassis_type");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString chassisType = file.readAll().trimmed();
        file.close();

        // Chassis types:
        // 3 - Desktop
        // 6 - Laptop 笔记本
        // 8 - Convertible - 可变(PC平板二合一) 翻转二合一，
        // 9 - Detachable 平板二合一，
        // 10 - Tablet  - 平板
        // 31 - All-in-One - 一体机。 （一体机也存在亮度节点,也算支持亮度调节把）
        if (chassisType == "6" ||
                chassisType == "8" ||
                chassisType == "9" ||
                chassisType == "10") {
            return true; // Laptop, Convertible, Detachable, Tablet
        }
    }

    return false; // Unable to read file
}
