package `in`.caresoft.carepulse.connect import android.content.Context import android.content.SharedPreferences import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey import org.json.JSONObject /** Encrypted storage for server URL, API token and the last config from the server. */ class Prefs private constructor(private val sp: SharedPreferences) { var server: String? get() = sp.getString("server", null); set(v) = sp.edit().putString("server", v).apply() var token: String? get() = sp.getString("token", null); set(v) = sp.edit().putString("token", v).apply() var configJson: String? get() = sp.getString("config", null); set(v) = sp.edit().putString("config", v).apply() /** Ward mode (shared phone): UHID of the patient being measured now. */ var wardUhid: String? get() = sp.getString("ward_uhid", null); set(v) = sp.edit().putString("ward_uhid", v).apply() var autoListen: Boolean get() = sp.getBoolean("auto_listen", false); set(v) = sp.edit().putBoolean("auto_listen", v).apply() var healthEnabled: Boolean get() = sp.getBoolean("health_on", false); set(v) = sp.edit().putBoolean("health_on", v).apply() var healthSyncedAt: Long? get() = sp.getLong("health_at", 0L).takeIf { it > 0 }; set(v) = sp.edit().putLong("health_at", v ?: 0L).apply() val isPaired get() = !server.isNullOrBlank() && !token.isNullOrBlank() val config: JSONObject? get() = configJson?.let { runCatching { JSONObject(it) }.getOrNull() } fun glucoseSeq(mac: String): Int? = sp.getInt("gseq_$mac", -1).takeIf { it >= 0 } fun setGlucoseSeq(mac: String, seq: Int) = sp.edit().putInt("gseq_$mac", seq).apply() fun clear() = sp.edit().clear().apply() companion object { @Volatile private var inst: Prefs? = null fun get(ctx: Context): Prefs = inst ?: synchronized(this) { inst ?: run { val key = MasterKey.Builder(ctx).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build() Prefs(EncryptedSharedPreferences.create(ctx, "carepulse", key, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM)) .also { inst = it } } } } }