package de.tsschulz.tt_tagebuch.shared.state

import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class AndroidClubStorage(
    context: Context,
) : ClubStorage {
    private val prefs = EncryptedSharedPreferences.create(
        context,
        PREFS_NAME,
        MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build(),
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
    )

    override suspend fun loadCurrentClubId(): Int? = withContext(Dispatchers.Default) {
        val value = prefs.getString(KEY_CURRENT_CLUB_ID, null) ?: return@withContext null
        value.toIntOrNull()
    }

    override suspend fun saveCurrentClubId(clubId: Int?) = withContext(Dispatchers.Default) {
        val editor = prefs.edit()
        if (clubId == null) editor.remove(KEY_CURRENT_CLUB_ID) else editor.putString(KEY_CURRENT_CLUB_ID, clubId.toString())
        editor.apply()
    }

    private companion object {
        private const val PREFS_NAME = "tttagebuch_club"
        private const val KEY_CURRENT_CLUB_ID = "currentClubId"
    }
}

