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

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.isidroid.c23.constant.Argument
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,
    savedStateHandle: SavedStateHandle
) : BaseViewModel<HomeContract.Event, HomeContract.State, HomeContract.Effect>() {

    init {
        viewModelScope.launch {
            savedStateHandle.getStateFlow<String?>(Argument.URI, null)
                .collect { uris ->
                    onCreate(uris)
                }
        }
    }


    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(uris: String?) {
        useCase.createSession(uris)
            .flowOn(Dispatchers.IO)
            .catchTimber { }
            .collect { res ->
                when (res) {
                    FlowResult.Loading -> setState { copy(isLoading = true) }
                    is FlowResult.Success -> setEffect { res.result }
                }
            }
    }
}

