package com.isidroid.c23.ui.screen.print_jobs

import androidx.lifecycle.viewModelScope
import com.isidroid.c23.domain.use_case.PrintJobsUseCase
import com.isidroid.c23.ext.isDebug
import com.isidroid.core.FlowResult
import com.isidroid.core.vm.BaseViewModel
import com.isidroid.utils.catchTimber
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

@HiltViewModel
class PrintJobsViewModel @Inject constructor(
    private val useCase: PrintJobsUseCase
) : BaseViewModel<PrintJobsContract.Event, PrintJobsContract.State, PrintJobsContract.Effect>() {
    init {
        viewModelScope.launch { load() }
    }

    override val isDebug: Boolean = isDebug()
    override fun setInitialState(): PrintJobsContract.State = PrintJobsContract.State()
    override suspend fun handleEvents(event: PrintJobsContract.Event) {
        when (event) {
            PrintJobsContract.Event.ToBack -> setEffect { PrintJobsContract.Effect.Navigation.ToBack }
        }
    }

    // handle events
    private suspend fun load() {
        useCase.load()
            .flowOn(Dispatchers.IO)
            .catchTimber { }
            .collect { res ->
                when (res) {
                    FlowResult.Loading -> setState { copy(loading = true) }
                    is FlowResult.Success -> setState { copy(loading = false, jobs = res.result) }
                }
            }
    }
    // handle callbacks
}