package com.atridad.magiccounter.ui.settings

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class AppSettingsViewModel(application: Application) : AndroidViewModel(application) {
    val themeMode: StateFlow<ThemeMode> =
        AppSettingsRepository.themeMode(application).stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = ThemeMode.System
        )

    fun setTheme(mode: ThemeMode) {
        viewModelScope.launch {
            AppSettingsRepository.setThemeMode(getApplication(), mode)
        }
    }

    val matchHistory: StateFlow<List<MatchRecord>> =
        AppSettingsRepository.readMatchHistory(application).stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = emptyList()
        )

    fun saveHistory(history: List<MatchRecord>) {
        viewModelScope.launch {
            AppSettingsRepository.writeMatchHistory(getApplication(), history)
        }
    }
}


