package de.tsschulz.tt_tagebuch.shared.state

import de.tsschulz.tt_tagebuch.shared.api.TrainingStatsApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class TrainingStatsManager(
    private val trainingStatsApi: TrainingStatsApi,
) {
    private val _state = MutableStateFlow(TrainingStatsState())
    val state: StateFlow<TrainingStatsState> = _state.asStateFlow()

    suspend fun loadStats(clubId: Int) {
        _state.value = _state.value.copy(isLoading = true, error = null)
        try {
            _state.value = _state.value.copy(stats = trainingStatsApi.getStats(clubId), isLoading = false)
        } catch (t: Throwable) {
            _state.value = _state.value.copy(isLoading = false, error = t.toUserMessage("Statistik konnte nicht geladen werden"))
        }
    }

    fun clear() {
        _state.value = TrainingStatsState()
    }
}
