package com.isidroid.c23.ui.screen.home

import androidx.lifecycle.viewModelScope
import com.isidroid.c23.domain.use_case.HomeUseCase
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.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val useCase: HomeUseCase
) : BaseViewModel<HomeContract.Event, HomeContract.State, HomeContract.Effect>() {
    init {
        viewModelScope.launch { onCreate() }
    }


    override val isDebug: Boolean = isDebug()
    override fun setInitialState(): HomeContract.State = HomeContract.State()
    override suspend fun handleEvents(event: HomeContract.Event) {}

    // handle events
    private suspend fun onCreate() {
        useCase.createSession()
            .flowOn(Dispatchers.IO)
            .catchTimber { }
            .collect { res ->
                when (res) {
                    FlowResult.Loading -> setState { copy(isLoading = true) }
                    is FlowResult.Success -> setEffect { res.result }
                }
            }
    }
}

