package com.casic.detector.vm

import androidx.lifecycle.MutableLiveData
import com.casic.detector.base.BaseApplication
import com.casic.detector.extensions.convertChinese
import com.casic.detector.extensions.separateResponseState
import com.casic.detector.extensions.toErrorMessage
import com.casic.detector.model.LoginResultModel
import com.casic.detector.retrofit.RetrofitServiceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.extensions.launch
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.vm.BaseViewModel
import com.pengxh.kt.lite.vm.LoadState

/**
 * 用户相关 VM
 * */
class UserViewModel : BaseViewModel() {
    private val gson by lazy { Gson() }

    val loginResult = MutableLiveData<LoginResultModel>()

    fun login(account: String, password: String) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.login(account, password)
        if (response.separateResponseState()) {
            loadState.value = LoadState.Success
            loginResult.value = gson.fromJson<LoginResultModel>(
                response, object : TypeToken<LoginResultModel>() {}.type
            )
        } else {
            loadState.value = LoadState.Fail
            response.toErrorMessage().show(BaseApplication.get())
        }
    }, {
        loadState.value = LoadState.Fail
        it.convertChinese().show(BaseApplication.get())
    })
}