package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.repository.HomeData
import de.trainingstagebuch.app.repository.HomeResult
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.utils.UiText
import de.trainingstagebuch.app.utils.ViewModelStateUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class HomeViewModel(application: Application) : AndroidViewModel(application) {

    private val homeService = AppServices.homeService

    private val _state = MutableStateFlow(HomeUiState())
    val state: StateFlow<HomeUiState> = _state.asStateFlow()

    init {
        load()
    }

    fun load() {
        viewModelScope.launch {
            _state.update { it.copy(status = HomeStatus.Loading, errorMessage = null) }
            when (val result = homeService.loadHomeData()) {
                is HomeResult.Success -> {
                    _state.update {
                        it.copy(
                            status = HomeStatus.Success,
                            data = result.data
                        )
                    }
                }

                is HomeResult.Error -> {
                    _state.update {
                        it.copy(
                            status = HomeStatus.Error,
                            errorMessage = ViewModelStateUtils.dynamicOrFallback(result.message)
                        )
                    }
                }
            }
        }
    }
}

data class HomeUiState(
    val status: HomeStatus = HomeStatus.Idle,
    val data: HomeData? = null,
    val errorMessage: UiText? = null
)

enum class HomeStatus {
    Idle,
    Loading,
    Success,
    Error
}
