package com.khmer9.yuki.screen.login

import android.util.Log
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.LoginRequest
import com.khmer9.yuki.remote.service.ApiService
import com.khmer9.yuki.util.Const
import com.khmer9.yuki.util.ModelPreferencesManager
import com.khmer9.yuki.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(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.resultCode == "1") {
                        _state.value = prev().copy(isProgress = false, isLoginSuccess = true)
                        prefHelper.setUserToken(it.data?.token ?: "")
                        prefHelper.setMinBetting(it.data?.user?.amountMin ?: 0)
                        prefHelper.setMaxBetting(it.data?.user?.amountMax ?: 0)
                        ModelPreferencesManager.put(it.data, Const.USER_KEY)
                        getLottoSet()
                    } 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 getLottoSet() {
        disposables.add(
            apiService.remoteLottoSet()
                .timeout(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Log.d("bettingType", it.toString())
                    if (it.resultCode == "1") {
                        it.data?.let { lottoList -> ModelPreferencesManager.putList(lottoList, Const.LOTTO_KEY) }
                    }
                }, {
                    val message: String = "ប្រតិបត្តិការមិនជោគជ័យ\n" + it.getErrorCode()
                    Log.d("bettingType", message)
                })
        )
    }

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