/* Copyright (c) KylinSoft  Co., Ltd. [2023].All rights reserved.
    [ostree-maintain-daemon] licensed under the [Your LICENSE].
    Author: [ZhangTingting]
    Create: [2024]
*/

#include "mm-log.h"
#include <assert.h>
#include <dbus/dbus-glib-lowlevel.h> //for mainloop
#include <dbus/dbus-glib.h>
#include <dbus/dbus.h>
#include <errno.h>
#include <fcntl.h>
#include <glib-2.0/glib.h>
#include <libintl.h> //gettext
#include <libnotify/notification.h>
#include <libnotify/notify-enum-types.h>
#include <libnotify/notify-features.h>
#include <libnotify/notify.h>
#include <linux/rtc.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

enum {
    MM_OPEN_SUCESS = 1,
    MM_OPEN_FAILED = 2,
    MM_CLOSE_SUCESS_CLEAR = 3, // 退出维护不保存
    MM_CLOSE_FAILED = 4,
    MM_MODE_STATUS = 5,
    NM_MODE_STATUS = 6,
    MM_CLOSE_SUCESS_SAVE = 7 // 退出维护保存
};

GMainLoop *mainloop;

int notifications(char *sigvalue)
{
    NotifyNotification *notification;
    gboolean success;
    GError *error = NULL;
    int reply_result = -1;
    if (!notify_init(gettext(" "))) // 主题
    {
        g_warning("mm-notify: Failed to initialize the notification function.");
        return 1;
    }

    notification = notify_notification_new(
        gettext("维护模式状态"), // 标题
        gettext(sigvalue),       // 内容
        "ukui-control-center");  // icon

    notify_notification_set_app_name(notification,"系统提示");

    if (notification == NULL) {
        g_warning("mm-notify: Failed to create the notification object.");
        return 1;
    }

    notify_notification_set_timeout(notification, 10 * 1000); // 10秒

    success = notify_notification_show(notification, &error);

    if (!success) {
        g_warning("mm-notify: Failed to show the notification: %s", error->message);
        g_error_free(error);
    } else {
        g_info("mm-notify: Notification displayed successfully.");
    }

    notify_uninit();
    return 0;
}

int main(int argc, char **argv)
{
    mm_log_init();
    setlocale(LC_ALL, "");
    bindtextdomain("mm-notify", "/usr/share/locale");
    textdomain("mm-notify");

    DBusConnection *connection;
    DBusError error;
    DBusMessage *message;
    DBusMessageIter iter;
    int reply_result = -1;

    dbus_error_init(&error); // 将错误对象连接到dbus

    /* connect to the daemon bus */
    connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
    if (connection == NULL) {
        g_info("mm-notify: Failed to get a system DBus connection.");
        fprintf(stderr, "Failed to get a system DBus connection: %s\n", error.message);
        exit(1);
    }
    g_info("mm-notify: Successfully connected to the system DBus.");

    dbus_bus_add_match(connection,
                       "type='signal',interface='com.kylin.MaintainMode.interface'",
                       &error);

    if (dbus_error_is_set(&error)) {
        g_warning("mm-notify: Match Error");
        fprintf(stderr, "Match Error (%s)\n", error.message);
        exit(1);
    }

    /*loop listening for signals being emmitted*/
    while (true) {
        dbus_connection_read_write(connection, 0);
        message = dbus_connection_pop_message(connection); // 等待消息

        // 没接收到等一秒钟继续
        if (NULL == message) {
            // g_info("mm-notify: No message received. Waiting...");
            sleep(1);
            continue;
        }

        // check if the message is the message we want to get
        if (dbus_message_is_signal(message, "com.kylin.MaintainMode.interface", "BootModeChanged")) {
            printf("notifications is ought to be send\n");
            if (!dbus_message_iter_init(message, &iter))
                fprintf(stderr, "MessageHas no Param");

            else {
                /*try to get the content of signal*/
                dbus_message_iter_get_basic(&iter, &reply_result);
                if (reply_result == -1) {
                    g_info("mm-notify: Failed to receive signal.");
                } else {
                    printf("mm-notify: Recetive Singal Value : %d\n", reply_result);
                    if (reply_result == MM_OPEN_SUCESS) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("维护模式开启成功\n需重启系统进入!");
                    } else if (reply_result == MM_MODE_STATUS) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("模式状态已切换，重启后生效");
                    } else if (reply_result == MM_OPEN_FAILED) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("维护模式开启失败");
                    } else if (reply_result == MM_CLOSE_SUCESS_CLEAR || reply_result == MM_CLOSE_SUCESS_SAVE) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("维护模式关闭成功\n需重启系统!");
                    } else if (reply_result == NM_MODE_STATUS) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("保持状态为用户模式");
                    } else if (reply_result == MM_CLOSE_FAILED) {
                        g_info("mm-notify: Recetive Singal Value : %d\n", reply_result);
                        notifications("维护模式关闭失败");
                    }
                }
            }
        }
    }
    // free the message
    dbus_message_unref(message);
    return 0;
}
