package com.khmer9.yuki.screen.setting

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.khmer9.yuki.app.getErrorCode
import com.khmer9.yuki.base.BaseViewModel
import com.khmer9.yuki.remote.service.ApiService
import com.khmer9.yuki.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(oldPassword: String, newPassword: String) {
        if (_state.value!!.isProgress) return
        _state.value = prev().copy(isProgress = true)

        disposables.add(
            apiService.updatePassword(oldPassword, newPassword)
                .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!!


}