package com.drivervault.phoneapp.car

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

/**
 * What the head unit knows about the phone's session.
 *
 * The car screens have no login of their own — a head unit is the last place to
 * type a password — so they read what the phone app has already persisted and
 * talk to the same API Server with the same token. That store is
 * shared_preferences' own file: one process, one set of preferences, so a server
 * switched on the phone is the server the car reads from, with nothing to keep
 * in step.
 *
 * The key names are lib/servers.dart's and lib/app_settings.dart's, with the
 * "flutter." prefix shared_preferences puts in front of every key it writes.
 * Change one there and change it here.
 */
object VaultStore {
    private const val FILE = "FlutterSharedPreferences"
    private const val PREFIX = "flutter."

    /** The server one request goes to: where it lives, and what identifies us. */
    data class Endpoint(val base: String, val token: String)

    /**
     * The active server and its session, or null when there is nothing to read
     * with — no server signed into yet, or the phone app never run since the
     * install.
     */
    fun endpoint(context: Context): Endpoint? {
        val prefs = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
        // Written by ServerRegistry rather than derived here: an untouched home
        // server carries no address of its own, its base being kDefaultApiBase —
        // a compile-time --dart-define this side of the app cannot see.
        val base = prefs.getString(PREFIX + "cc_active_base", "").orEmpty().trim()
        val id = prefs.getString(PREFIX + "cc_active_server", "home").orEmpty()
        val raw = prefs.getString(PREFIX + "cc_session_$id", null) ?: return null
        val token = runCatching { JSONObject(raw).optString("token") }.getOrDefault("")
        if (base.isEmpty() || token.isEmpty()) return null
        return Endpoint(base, token)
    }

    /** The signed-in user's BCP-47 tag, which picks the language and the number formats. */
    fun locale(context: Context): String =
        context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
            .getString(PREFIX + "cc_locale", "en-US")
            .let { if (it.isNullOrBlank()) "en-US" else it }

    /** The user's chosen date format: YMD | DMY_NUM | DMY | MDY, as in format.dart. */
    fun dateFormat(context: Context): String =
        context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
            .getString(PREFIX + "cc_dateFormat", "YMD")
            .let { if (it.isNullOrBlank()) "YMD" else it }
}
