package com.sambath.klaklouk_main.screen.main.cflive.currentbets

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

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

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