package com.casic.br.vm

import androidx.lifecycle.MutableLiveData
import com.casic.br.base.BaseApplication
import com.casic.br.extensions.separateResponseCode
import com.casic.br.extensions.toErrorMessage
import com.casic.br.model.PublicKeyModel
import com.casic.br.utils.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

class AuthenticateViewModel : BaseViewModel() {

    private val gson by lazy { Gson() }
    val keyModel = MutableLiveData<PublicKeyModel>()

    fun obtainPublicKey() = launch({
        val response = RetrofitServiceManager.authenticate()
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            keyModel.value = gson.fromJson<PublicKeyModel>(
                response, object : TypeToken<PublicKeyModel>() {}.type
            )
        } else {
            response.toErrorMessage().show(BaseApplication.obtainInstance())
        }
    }, {
        it.printStackTrace()
    })
}