package com.sambath.sbc.screen.setting

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.ChangePwd
import com.sambath.sbc.remote.NewPassword
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 SettingViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel() {
    private val _state = MutableLiveData<UpdatePwdViewState>(UpdatePwdViewState())
    val state: LiveData<UpdatePwdViewState> = _state
    fun updatePassword(changePwd: ChangePwd) {
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)
        disposables.add(
            apiService.changePassword(changePwd)
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
                        _state.value = prev().copy(isProgress = false, isUpdateSuccess = true)
                        prefHelper.logout()
                    } 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)
                })
        )
    }

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