package com.tsmobile.app.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first

private val Context.identityDataStore by preferencesDataStore(name = "teamspeak_identity")

class IdentityStore(private val context: Context) {

    companion object {
        private val IDENTITY_KEY = stringPreferencesKey("identity")
    }

    suspend fun getOrCreate(generate: () -> String): String {
        val stored = context.identityDataStore.data.first()[IDENTITY_KEY]
        if (!stored.isNullOrBlank()) return stored

        val generated = generate()
        if (generated.isBlank()) return ""
        context.identityDataStore.edit { preferences ->
            if (preferences[IDENTITY_KEY].isNullOrBlank()) {
                preferences[IDENTITY_KEY] = generated
            }
        }
        return context.identityDataStore.data.first()[IDENTITY_KEY].orEmpty()
    }
}
