/*
 * Copyright (C) 2023, 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 "notification-global-settings.h"
#include <QJsonObject>
#include <QQmlEngine>
#include <QDBusInterface>
#include <QDBusReply>
#include <QDBusMessage>
#include <QDebug>
#include <QTimer>
#include "settings-manager.h"
#include "settings-properties.h"
#include "settings-properties-info.h"
namespace UkuiNotification{
class NotificationGlobalSettingsPrivate
{
    friend class NotificationGlobalSettings;
public:
    ~NotificationGlobalSettingsPrivate()
    {
        if (m_usdInterface) {
            delete m_usdInterface;
            m_usdInterface = nullptr;
        }
        if(m_timeChecktimer) {
            delete m_timeChecktimer;
            m_timeChecktimer = nullptr;
        }
    }
private:
    QJsonObject m_settings;
    QDBusInterface *m_usdInterface = nullptr;
    int m_currentScreenMode = 0; //0-仅主屏；1-镜像；2-扩展；3-仅副屏
    QTimer *m_timeChecktimer = nullptr;
    bool m_isDnD = false;
};
}

using namespace UkuiNotification;// UkuiNotification
NotificationGlobalSettings::NotificationGlobalSettings(QObject *parent) : QObject(parent), d(new NotificationGlobalSettingsPrivate())
{
    qmlRegisterUncreatableType<UkuiNotification::NotificationGlobalSettings>("org.ukui.notification.client", 1, 0, "NotificationGlobalSettings", "");
    connect(SettingsManager::self(), &SettingsManager::settingsDataChanged, this, &NotificationGlobalSettings::settingsDataChanged);
    d->m_settings = SettingsManager::self()->getGlobalSettings();
    d->m_usdInterface = new QDBusInterface("org.ukui.SettingsDaemon",
                                           "/org/ukui/SettingsDaemon/xrandr",
                                           "org.ukui.SettingsDaemon.xrandr");
    if(!d->m_usdInterface->isValid()) {
        qWarning() << "NotificationGlobalSettings: Fail to creat org.ukui.SettingsDaemon dbus interface!";
        return;
    }
    QDBusReply<int> reply = d->m_usdInterface->call("getScreenMode", "ukui-notification-server");
    if (reply.isValid()) {
        d->m_currentScreenMode = reply.value();
    } else {
        qWarning()<<"NotificationGlobalSettings: Call getScreenMode failed!";
    }
    connect(d->m_usdInterface, SIGNAL(screenModeChanged(int)), this, SLOT(screenModeChanged(int)));

    d->m_timeChecktimer = new QTimer;
    d->m_timeChecktimer->setSingleShot(true);
    //设置为精密定时器
    d->m_timeChecktimer->setTimerType(Qt::PreciseTimer);
    connect(d->m_timeChecktimer, &QTimer::timeout, this, &NotificationGlobalSettings::checkTimeForDND);

    d->m_isDnD = isDND();
    checkTimeForDND();
}

NotificationGlobalSettings::~NotificationGlobalSettings()
{
    if(d) {
        delete d;
        d = nullptr;
    }
}

bool NotificationGlobalSettings::scheduleTurnOnDND()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDND).name()).toVariant().toBool();
}

QTime NotificationGlobalSettings::scheduleTurnOnDNDTime()
{
    return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDNDTime).name()).toString(), "HHmm");
}

QTime NotificationGlobalSettings::scheduleTurnOffDNDTime()
{
    return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOffDNDTime).name()).toString(), "HHmm");
}

bool NotificationGlobalSettings::DNDWhileMultiScreen()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileMultiScreen).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::DNDWhileFullScreen()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileFullScreen).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::notifyAlarmWhileDND()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::NotifyAlarmWhileDND).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::receiveNotificationsFromApps()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ReceiveNotificationsFromApps).name()).toVariant().toBool();
}

void NotificationGlobalSettings::settingsDataChanged()
{
    QJsonObject data = SettingsManager::self()->getGlobalSettings();
    for(SettingsProperty::Property property : GLOBAL_SETTINGS) {
        QString name = SettingsPropertiesInfo(property).name();
        QJsonValue value = data.value(name);
        if(d->m_settings.value(name) != value) {
            d->m_settings.insert(name, value);
            switch (property) {
                case SettingsProperty::ScheduleTurnOnDND:
                    Q_EMIT scheduleTurnOnDNDChanged(value.toVariant().toBool());
                    checkTimeForDND();
                    break;
                case SettingsProperty::ScheduleTurnOnDNDTime:
                    Q_EMIT scheduleTurnOnDNDTimeChanged(QTime::fromString(value.toString(), "HHmm"));
                    checkTimeForDND();
                    break;
                case SettingsProperty::ScheduleTurnOffDNDTime:
                    Q_EMIT scheduleTurnOffDNDTimeChanged(QTime::fromString(value.toString(), "HHmm"));
                    checkTimeForDND();
                    break;
                case SettingsProperty::DNDWhileMultiScreen:
                    Q_EMIT DNDWhileMultiScreenChanged(value.toVariant().toBool());
                    checkDNDMode();
                    break;
                case SettingsProperty::DNDWhileFullScreen:
                    Q_EMIT DNDWhileFullScreenChanged(value.toVariant().toBool());
                    checkDNDMode();
                    break;
                case SettingsProperty::NotifyAlarmWhileDND:
                    Q_EMIT notifyAlarmWhileDNDChanged(value.toVariant().toBool());
                    break;
                case SettingsProperty::ReceiveNotificationsFromApps:
                    Q_EMIT receiveNotificationsFromAppsChanged(value.toVariant().toBool());
                    break;
                default:
                    break;
            }
        }
    }
}

void NotificationGlobalSettings::setScheduleTurnOnDND(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDND, enable);
}

void NotificationGlobalSettings::setScheduleTurnOnDNDTime(const QTime &time)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDNDTime, time);
}

void NotificationGlobalSettings::setScheduleTurnOffDNDTime(const QTime &time)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOffDNDTime, time);
}

void NotificationGlobalSettings::setDNDWhileMultiScreen(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileMultiScreen, enable);
}

void NotificationGlobalSettings::setDNDWhileFullScreen(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileFullScreen, enable);
}

void NotificationGlobalSettings::setNotifyAlarmWhileDND(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::NotifyAlarmWhileDND, enable);
}

void NotificationGlobalSettings::setReceiveNotificationsFromApps(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ReceiveNotificationsFromApps, enable);
}

bool NotificationGlobalSettings::isDND() {
    bool dnd = false;
    if(scheduleTurnOnDND()) {
        const QTime currentTime = QTime::currentTime();
        const QTime dndOnTime = scheduleTurnOnDNDTime();
        const QTime dndOffTime = scheduleTurnOffDNDTime();
        if (dndOnTime > dndOffTime) {
            dnd = (currentTime >= dndOnTime) || (currentTime < dndOffTime);
        } else {
            dnd = (currentTime >= dndOnTime) && (currentTime < dndOffTime);
        }
    }
    if(!dnd) {
        if(DNDWhileMultiScreen()) {
            if(d->m_currentScreenMode == 1 || d->m_currentScreenMode == 2) {
                dnd = true;
            }
        }
    }
    if(!dnd) {
        if(DNDWhileFullScreen()) {
            QDBusMessage msg = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"),
                                                              QStringLiteral("/KWin"),
                                                              QStringLiteral("org.kde.KWin"),
                                                              QStringLiteral("haveFullScreenActiveWindow"));
            QDBusReply<bool> reply  = QDBusConnection::sessionBus().call(msg);
            if(reply.isValid()) {
                dnd = reply.value();
            }
        }
    }
    return dnd;
}

void NotificationGlobalSettings::screenModeChanged(int mode)
{
    qDebug() << "NotificationGlobalSettings::screenModeChanged : " << mode;
    d->m_currentScreenMode = mode;
    checkDNDMode();
}

void NotificationGlobalSettings::checkDNDMode()
{
    bool dnd = isDND();
    if (d->m_isDnD != dnd)
    {
        qDebug() << "NotificationGlobalSettings::checkDNDMode DND is changed: " << dnd;
        d->m_isDnD = dnd;
        Q_EMIT dndChanged(dnd);
    }
}

void NotificationGlobalSettings::checkTimeForDND()
{
    checkDNDMode();
    if (!scheduleTurnOnDND()) {
        // 勿扰模式开关关闭，关闭定时器
        if (d->m_timeChecktimer->isActive()) {
            d->m_timeChecktimer->stop();
        }
        return;
    }

    QTime currentTime = QTime::currentTime();
    QTime dndOnTime = scheduleTurnOnDNDTime();
    QTime dndOffTime = scheduleTurnOffDNDTime();

    int msec = 0;
    if (dndOnTime > dndOffTime)
    {
        if (currentTime >= dndOffTime && currentTime < dndOnTime) {
            msec = currentTime.msecsTo(dndOnTime);
        } else {
            msec = currentTime.msecsTo(dndOffTime);
        }
    } else {
        if (currentTime >= dndOnTime && currentTime < dndOffTime) {
            msec = currentTime.msecsTo(dndOffTime);
        } else {
            msec = currentTime.msecsTo(dndOnTime);
        }
    }
    //跨天处理
    static constexpr int MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
    if (msec < 0) {
        msec += MILLISECONDS_PER_DAY;
    }

    if (d->m_timeChecktimer->isActive()) {
        d->m_timeChecktimer->stop();
    }
    d->m_timeChecktimer->start(msec);
}