package com.sambath.kunkhmer.screen.login

import android.util.Log
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.remote.LoginRequest
import com.sambath.kunkhmer.util.Const
import com.sambath.kunkhmer.util.ModelPreferencesManager
import com.sambath.kunkhmer.util.PrefHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

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

    fun login(username: String, password: String) {
        if (_state.value!!.isProgress) return
        val request = LoginRequest(username, password)
        _state.value = prev().copy(isProgress = true)

        disposables.add(
            apiService.login(request)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Log.d("login", it.toString())
                    if (it.resultCode == 1) {
                        _state.value = prev().copy(isProgress = false, isLoginSuccess = true, userName = it.data?.user?.userName)
                        prefHelper.setUserToken(it.data?.token ?: "")
                        prefHelper.setChannelType(1)
                        ModelPreferencesManager.put(it.data?.user, Const.USER_KEY)
                    } else {
                        _state.value =
                            prev().copy(isProgress = false, error = "[${it.message.description}]")
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
                    _state.value = prev().copy(isProgress = false, error = message)
                })
        )
    }

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