package com.sambath.kunkhmer.screen.main.cflive.result

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

class CfResultViewModel (val apiService: ApiService, val prefHelper: PrefHelper): BaseViewModel() {
    private val _state = MutableLiveData<CfResultViewState>(CfResultViewState())
    val state: LiveData<CfResultViewState> = _state
    fun getCfResuleData(){
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)
        disposables.add(
            apiService.getResult()
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
//                        Log.d("dataxzsd", it.data.toString())
                        _state.value = prev().copy(
                            isProgress = false,
                            error = null,
                            isSuccess = true,
                            resultList = it.data?.results,
                            resultSummary = it.data?.resultSummary
                        )
                    } else {
                        _state.value =
                            prev().copy(
                                isProgress = false,
                                isSuccess = false,
                                error = "[${it.message.description}]"
                            )
                    }
                }, {
//                    Log.d("dataxzsd", it.getErrorCode())
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.getErrorCode()
                    _state.value = prev().copy(
                        isProgress = false,
                        isSuccess = false,
                        error = message
                    )
                })
        )
    }

    private fun prev() = _state.value!!
}