package com.seven.ikar.kotlin.feature.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.settings.AppSettingsSnapshot
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class AppSettingsUiState(
    val snapshot: AppSettingsSnapshot = AppSettingsSnapshot()
)

class AppSettingsViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(AppSettingsUiState(snapshot = container.appSettings.loadSnapshot()))
    val uiState: StateFlow<AppSettingsUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            container.appSettings.snapshot.collect { snapshot ->
                _uiState.value = AppSettingsUiState(snapshot = snapshot)
            }
        }
    }

    fun updateSnapshot(transform: (AppSettingsSnapshot) -> AppSettingsSnapshot) {
        container.appSettings.update(transform)
    }

    fun reset() {
        container.appSettings.reset()
    }
}
