package ru.myitschool.work.ui.qr.result

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import ru.myitschool.work.domain.profile.OpenByQrUseCase
import ru.myitschool.work.utils.MutablePublishFlow
import javax.inject.Inject
import dagger.Lazy
import ru.myitschool.work.R

@HiltViewModel
class QrResultViewModel @Inject constructor(
    @ApplicationContext private val context: Context,
    private val openByQrUseCase: Lazy<OpenByQrUseCase>,
) : ViewModel() {

    private val _action = MutablePublishFlow<Action>()
    val action = _action.asSharedFlow()

    private val _state = MutableStateFlow<State>(initialState)
    val state = _state.asStateFlow()

    fun clickClose() {
        viewModelScope.launch {
            _action.emit(Action.Close)
        }
    }

    fun setScanResult(content: String?) {
        viewModelScope.launch {
            _state.update { State.Loading }
            val statusText = if (content == null) {
                R.string.qr_result_status_cancel
            } else {
                openByQrUseCase.get().invoke(content).fold(
                    onSuccess = { R.string.qr_result_status_success },
                    onFailure = { R.string.qr_result_status_error }
                )
            }
            _state.update {
                State.Show(
                    status = context.resources.getString(statusText)
                )
            }
        }
    }

    sealed interface Action {
        data object Close : Action
    }

    sealed interface State {
        data object Loading : State

        data class Show(
            val status: String
        ) : State
    }

    private companion object {
        val initialState = State.Loading
    }
}