package com.casic.electric.detector.vm

import androidx.lifecycle.MutableLiveData
import com.casic.electric.detector.base.BaseApplication
import com.casic.electric.detector.extensions.separateResponseState
import com.casic.electric.detector.extensions.toErrorMessage
import com.casic.electric.detector.model.LoginResultModel
import com.casic.electric.detector.retrofit.RetrofitServiceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.extensions.isNetworkConnected
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
        if (BaseApplication.get().isNetworkConnected()) {
            "连接服务器失败，IP或端口错误".show(BaseApplication.get())
        } else {
            "网络连接失败".show(BaseApplication.get())
        }
    })
}