package com.cocking.fight.screen.dialogfragment

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.sambath.sbc.app.getErrorCode
import com.sambath.sbc.base.BaseViewModel
import com.sambath.sbc.remote.service.ApiService
import com.sambath.sbc.util.PrefHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class StatementDialogViewModel (val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel(){
    private val _stateThree = MutableLiveData<StatementDialogViewState>(StatementDialogViewState())
    val stateThree: LiveData<StatementDialogViewState> = _stateThree

    fun getReportThree() {
        if (_stateThree.value!!.isProgressThree) return
        _stateThree.value = prevThree().copy(isProgressThree = true)
        disposables.add(
            apiService.getReportThree()
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
                        _stateThree.value = prevThree().copy(
                            isProgressThree = false,
                            errorThree = null,
                            reportThreeList = it.data
                        )
                    } else {
                        _stateThree.value = prevThree().copy(isProgressThree = false, errorThree = "[${it.message.description}]")
                    }
                }, {
                    val message : String ="ប្រតិបត្តិការមិនជោគជ័យ\n"+it.getErrorCode()
                    _stateThree.value = prevThree().copy(isProgressThree = false, errorThree = message)
                })
        )
    }

    private fun prevThree() = _stateThree.value!!
}