/*
 * Hermes Node Android
 * Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package net.nexlab.hermesnodeandroid

import android.app.Notification
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import org.json.JSONArray
import org.json.JSONObject

class HermesNotificationListenerService : NotificationListenerService() {
    override fun onListenerConnected() {
        NotificationSessionStore.putStatus(this, true)
        refreshSnapshot(activeNotifications.orEmpty())
    }

    override fun onListenerDisconnected() {
        NotificationSessionStore.putStatus(this, false)
    }

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        refreshSnapshot(activeNotifications.orEmpty())
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        refreshSnapshot(activeNotifications.orEmpty())
    }

    private fun refreshSnapshot(notifications: Array<out StatusBarNotification>) {
        val arr = JSONArray()
        notifications.sortedByDescending { it.postTime }.forEach { sbn ->
            arr.put(sbn.toJson())
        }
        NotificationSessionStore.saveSnapshot(this, arr)
    }
}

private fun StatusBarNotification.toJson(): JSONObject {
    val extras = notification.extras
    val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
    val text = extras?.getCharSequence(Notification.EXTRA_TEXT)?.toString().orEmpty()
    val subText = extras?.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty()
    val bigText = extras?.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString().orEmpty()
    return JSONObject()
        .put("key", key)
        .put("package_name", packageName)
        .put("post_time", postTime)
        .put("is_ongoing", isOngoing)
        .put("is_clearable", isClearable)
        .put("id", id)
        .put("tag", tag ?: "")
        .put("title", title)
        .put("text", text)
        .put("sub_text", subText)
        .put("big_text", bigText)
        .put("has_content_intent", notification.contentIntent != null)
        .put("category", notification.category ?: "")
        .put("channel_id", notification.channelId ?: "")
}
