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

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

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