package com.khmer9.cflivemain.screen.main

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

class TokenViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel() {
    private val _state = MutableLiveData(TokenViewState())
    val state: LiveData<TokenViewState> = _state

    private fun prev() = _state.value!!

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