package com.example.maposition

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

data class Group(val name: String, val phones: List<String>)

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 phones = mutableListOf<String>()
                val pa = o.getJSONArray("phones")
                for (j in 0 until pa.length()) phones.add(pa.getString(j))
                groups.add(Group(o.getString("name"), phones))
            }
        } else {
            // Migration depuis l'ancien format : 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))
                saveGroups(ctx, groups)
            }
        }
        return groups
    }

    fun saveGroups(ctx: Context, groups: List<Group>) {
        val arr = JSONArray()
        groups.forEach { g ->
            arr.put(JSONObject().put("name", g.name).put("phones", JSONArray(g.phones)))
        }
        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()
    }
}
