package ru.fincode.tsudesk.feature.schedule.presentation.screen

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import ru.fincode.tsudesk.core.common.log.logD
import ru.fincode.tsudesk.core.common.log.logE
import ru.fincode.tsudesk.core.common.model.DataResult
import ru.fincode.tsudesk.feature.schedule.domain.model.ScheduleType
import ru.fincode.tsudesk.feature.schedule.domain.usecase.ObserveScheduleUseCase
import ru.fincode.tsudesk.feature.schedule.presentation.model.ScheduleUiState
import javax.inject.Inject

@HiltViewModel
class ScheduleViewModel @Inject constructor(
    private val observeScheduleUseCase: ObserveScheduleUseCase
) : ViewModel() {

    private val scheduleType = ScheduleType.Group(number = "220631")

    val state: StateFlow<ScheduleUiState> = observeScheduleUseCase(scheduleType).map { result ->
        when (result) {
            is DataResult.Data -> {
                logD("${if (result.refreshedFromNetwork) "NETWORK" else "CACHE"}: ${result.data}")
                ScheduleUiState(
                    isLoading = false,
                    data = result.data,
                    refreshedFromNetwork = result.refreshedFromNetwork
                )
            }

            is DataResult.Error -> {
                logE("Error loading schedule: ${result.error}")
                ScheduleUiState(isLoading = false, errorMessage = result.error.toString())
            }
        }
    }.onStart {
        logD("Start collecting schedule flow")
        emit(ScheduleUiState(isLoading = true))
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = ScheduleUiState(isLoading = true)
    )
}
