package uz.mobiuz.mobiservice.dev.ui.sdk.history

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import uz.agr.sdk.core.entity.card.CardInfo
import uz.agr.sdk.pgw_core.mobi.CardListenerMobi
import uz.agr.sdk.pgw_core.mobi.MobiUz
import uz.mobiuz.mobiservice.dev.model.Monitoring
import uz.mobiuz.mobiservice.dev.network.model.UiStateList
import uz.mobiuz.mobiservice.dev.network.repository.CardRepository
import uz.mobiuz.mobiservice.dev.network.repository.MainRepository
import javax.inject.Inject

@HiltViewModel
class HistoryViewModel @Inject constructor(
    private val repository: CardRepository
) : ViewModel() {

    fun addMonitoring(data: Monitoring) = viewModelScope.launch {
        repository.addMonitoring(data)
    }

    private val _cardListUiState = MutableSharedFlow<UiStateList<CardInfo>>()
    val cardListUiState: SharedFlow<UiStateList<CardInfo>> = _cardListUiState

    fun getAllCards() = viewModelScope.launch {
        _cardListUiState.emit(UiStateList.LOADING)
        MobiUz.getAllCards(object : CardListenerMobi<CardInfo> {
            override fun error(message: String) {
                viewModelScope.launch {
                    _cardListUiState.emit(UiStateList.ERROR(message))
                }
            }

            override fun loading(boolean: Boolean) {}

            override fun local(localData: List<CardInfo>) {
                viewModelScope.launch {
                    _cardListUiState.emit(UiStateList.SUCCESS(localData))
                }
            }

            override fun server(serverData: List<CardInfo>) {
                viewModelScope.launch {
                    _cardListUiState.emit(UiStateList.SUCCESS(serverData))
                }
            }
        })
    }
    }