package com.example.maposition

import android.content.Context
import org.json.JSONArray
import org.json.JSONObject

data class Recipient(val name: String, val phone: String)

data class Group(val name: String, val recipients: List<Recipient>) {
    val phones: List<String> get() = recipients.map { it.phone }

    /** "Alice, Bob, 0611…" — le nom si renseigné, sinon le numéro. */
    fun displayList(): String =
        recipients.joinToString(", ") { it.name.ifBlank { it.phone } }
}

object Prefs {
    private const val FILE = "MaPositionPrefs"

    private fun sp(ctx: Context) = ctx.getSharedPreferences(FILE, Context.MODE_PRIVATE)

    fun getName(ctx: Context): String = sp(ctx).getString("name", "") ?: ""

    fun setName(ctx: Context, name: String) {
        sp(ctx).edit().putString("name", name.trim()).apply()
    }

    fun getGroups(ctx: Context): MutableList<Group> {
        val raw = sp(ctx).getString("groups", null)
        val groups = mutableListOf<Group>()
        if (raw != null) {
            val arr = JSONArray(raw)
            for (i in 0 until arr.length()) {
                val o = arr.getJSONObject(i)
                val recipients = mutableListOf<Recipient>()
                val ra = o.optJSONArray("recipients")
                if (ra != null) {
                    for (j in 0 until ra.length()) {
                        val ro = ra.getJSONObject(j)
                        recipients.add(Recipient(ro.optString("name", ""), ro.getString("phone")))
                    }
                } else {
                    // Migration depuis le format v1.4 : numéros sans nom
                    val pa = o.optJSONArray("phones")
                    if (pa != null) {
                        for (j in 0 until pa.length()) recipients.add(Recipient("", pa.getString(j)))
                    }
                }
                groups.add(Group(o.getString("name"), recipients))
            }
        } else {
            // Migration depuis le format v1.0-1.3 : liste unique de numéros
            val legacy = sp(ctx).getString("phones", "") ?: ""
            val phones = legacy.split(";").map { it.trim() }.filter { it.isNotEmpty() }
            if (phones.isNotEmpty()) {
                groups.add(Group(ctx.getString(R.string.default_group_name), phones.map { Recipient("", it) }))
                saveGroups(ctx, groups)
            }
        }
        return groups
    }

    fun saveGroups(ctx: Context, groups: List<Group>) {
        val arr = JSONArray()
        groups.forEach { g ->
            val ra = JSONArray()
            g.recipients.forEach { r ->
                ra.put(JSONObject().put("name", r.name).put("phone", r.phone))
            }
            arr.put(JSONObject().put("name", g.name).put("recipients", ra))
        }
        sp(ctx).edit().putString("groups", arr.toString()).apply()
    }

    fun getActiveGroupName(ctx: Context): String = sp(ctx).getString("activeGroup", "") ?: ""

    fun setActiveGroupName(ctx: Context, name: String) {
        sp(ctx).edit().putString("activeGroup", name).apply()
    }

    /** Groupe actif, ou le premier groupe si l'actif n'existe plus. */
    fun getActiveGroup(ctx: Context): Group? {
        val groups = getGroups(ctx)
        if (groups.isEmpty()) return null
        return groups.find { it.name == getActiveGroupName(ctx) } ?: groups.first()
    }
}
