Pith - timber
package com.vgmlr.timber

import android.content.Context
import androidx.core.content.edit
import org.json.JSONObject

internal const val FMT_M4A = "m4a"
internal const val FMT_WAV = "wav"
internal const val PREFIX_DEFAULT = "timber_"
internal const val DIR_DEFAULT = "Recordings"

private const val K_FORMAT = "format"
private const val K_HIGH = "high"
private const val K_DIR = "dir"
private const val K_PREFIX = "prefix"
private const val K_NOTIFY = "notify"
private const val K_NEWEST = "newest"
private const val K_ASKED = "asked"
private const val K_IDS = "ids"
private const val K_NEXT = "next_id"

internal class TimberPrefs(ctx: Context) {
    private val sp = ctx.getSharedPreferences("timber_prefs", Context.MODE_PRIVATE)

    var format: String
        get() = sp.getString(K_FORMAT, FMT_M4A) ?: FMT_M4A
        set(v) = sp.edit { putString(K_FORMAT, v) }

    var high: Boolean
        get() = sp.getBoolean(K_HIGH, true)
        set(v) = sp.edit { putBoolean(K_HIGH, v) }

    var dir: String
        get() = sp.getString(K_DIR, "") ?: ""
        set(v) = sp.edit { putString(K_DIR, v) }

    var prefix: String
        get() = sp.getString(K_PREFIX, PREFIX_DEFAULT) ?: PREFIX_DEFAULT
        set(v) = sp.edit { putString(K_PREFIX, v) }

    var notify: Boolean
        get() = sp.getBoolean(K_NOTIFY, true)
        set(v) = sp.edit { putBoolean(K_NOTIFY, v) }

    var newest: Boolean
        get() = sp.getBoolean(K_NEWEST, true)
        set(v) = sp.edit { putBoolean(K_NEWEST, v) }

    var asked: Boolean
        get() = sp.getBoolean(K_ASKED, false)
        set(v) = sp.edit { putBoolean(K_ASKED, v) }

    val nextId: Int get() = sp.getInt(K_NEXT, 1)

    fun ids(): MutableMap<String, Int> {
        val o = runCatching { JSONObject(sp.getString(K_IDS, "{}") ?: "{}") }.getOrElse { JSONObject() }
        return o.keys().asSequence().associateWith { o.optInt(it) }.toMutableMap()
    }

    fun saveIds(map: Map<String, Int>, next: Int) = sp.edit {
        putString(K_IDS, JSONObject(map).toString())
        putInt(K_NEXT, next)
    }
}