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.model.VersionResultModel
import com.casic.detector.retrofit.RetrofitServiceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.base.BaseViewModel
import com.pengxh.kt.lite.extensions.launch
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.LoadState

class VersionViewModel : BaseViewModel() {
    private val gson by lazy { Gson() }

    val versionResult = MutableLiveData<VersionResultModel>()

    fun getApplicationVersion() = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.getApplicationVersion()
        versionResult.value = gson.fromJson<VersionResultModel>(
            response, object : TypeToken<VersionResultModel>() {}.type
        )
        loadState.value = LoadState.Success
    }, {
        loadState.value = LoadState.Fail
        it.convertChinese().show(BaseApplication.get())
    })
}