package ru.forbion.f7cloud.feature.notes

import org.json.JSONArray
import org.json.JSONObject

/**
 * Заметка (Notes API v1). Поля контракта: id, etag, readonly, content, title, category,
 * favorite, modified. Источник модели — `nextcloud/notes` v5.0.0 (карта app-map/notes.md).
 */
data class Note(
    val id: Long,
    val etag: String = "",
    val readonly: Boolean = false,
    val title: String = "",
    val category: String = "",
    val content: String = "",
    val favorite: Boolean = false,
    val modified: Long = 0L,
) {
    companion object {
        /** Разбор одной заметки из JSON ответа API v1. */
        fun fromJson(obj: JSONObject): Note = Note(
            id = obj.optLong("id", 0L),
            etag = obj.optString("etag"),
            readonly = obj.optBoolean("readonly", false),
            title = obj.optString("title"),
            category = obj.optString("category"),
            content = obj.optString("content"),
            favorite = obj.optBoolean("favorite", false),
            modified = obj.optLong("modified", 0L),
        )

        /** Разбор списка заметок (GET /notes, в т.ч. с exclude=content). */
        fun listFromJson(array: JSONArray): List<Note> {
            val out = ArrayList<Note>(array.length())
            for (i in 0 until array.length()) {
                val obj = array.optJSONObject(i)
                if (obj != null && obj.optLong("id", 0L) > 0L) {
                    out += fromJson(obj)
                }
            }
            return out
        }
    }
}
