package ru.forbion.f7cloud.core.network

import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
data class F7Notification(
    val id: Long,
    val subject: String,
    val message: String,
    val datetime: String,
    val link: String,
    val app: String,
    val icon: String = "",
)

class NotificationsRepository {
    fun load(
        serverUrl: String,
        username: String,
        appPassword: String,
        trustAllCerts: Boolean = false,
        limit: Int = 50,
    ): List<F7Notification> {
        val client = NetworkFactory.newAuthedClient(username, appPassword, trustAllCerts)
        val url = "${serverUrl.trimEnd('/')}/ocs/v2.php/apps/notifications/api/v2/notifications" +
            "?format=json&limit=$limit"
        val request = Request.Builder()
            .url(url)
            .header("OCS-APIRequest", "true")
            .header("Accept", "application/json")
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful || response.body == null) {
                error("Уведомления HTTP ${response.code}")
            }
            val ocs = JSONObject(response.body!!.string()).optJSONObject("ocs")
                ?: error("Некорректный ответ уведомлений")
            val meta = ocs.optJSONObject("meta")
            if (meta?.optString("status").equals("failure", ignoreCase = true)) {
                error(meta?.optString("message").orEmpty().ifBlank { "Ошибка уведомлений" })
            }
            val data = ocs.opt("data")
            val array = when (data) {
                is JSONArray -> data
                is JSONObject -> JSONArray().put(data)
                else -> JSONArray()
            }
            return parseNotifications(array)
        }
    }

    private fun parseNotifications(array: JSONArray): List<F7Notification> {
        val out = mutableListOf<F7Notification>()
        for (i in 0 until array.length()) {
            val obj = array.optJSONObject(i) ?: continue
            val id = obj.optLong("notification_id", 0L)
            if (id <= 0L) continue
            val subject = obj.optString("subject").ifBlank { obj.optString("app") }
            out += F7Notification(
                id = id,
                subject = subject,
                message = obj.optString("message"),
                datetime = obj.optString("datetime"),
                link = obj.optString("link"),
                app = obj.optString("app"),
                icon = obj.optString("icon"),
            )
        }
        return out
    }

    fun dismiss(
        serverUrl: String,
        username: String,
        appPassword: String,
        notificationId: Long,
        trustAllCerts: Boolean = false,
    ) {
        val client = NetworkFactory.newAuthedClient(username, appPassword, trustAllCerts)
        val url = "${serverUrl.trimEnd('/')}/ocs/v2.php/apps/notifications/api/v2/notifications/$notificationId"
        val request = Request.Builder()
            .url(url)
            .delete()
            .header("OCS-APIRequest", "true")
            .header("Accept", "application/json")
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                error("Уведомления HTTP ${response.code}")
            }
        }
    }
}
