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.BannerImageModel
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 BannerViewModel : BaseViewModel() {

    private val gson by lazy { Gson() }
    val listModel = MutableLiveData<BannerImageModel>()

    fun obtainBanner(bannerName: String, bannerModule: String) = launch({
        val response = RetrofitServiceManager.obtainBanner(bannerName, bannerModule)
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            listModel.value = gson.fromJson<BannerImageModel>(
                response, object : TypeToken<BannerImageModel>() {}.type
            )
        } else {
            response.toErrorMessage().show(BaseApplication.obtainInstance())
        }
    }, {
        it.printStackTrace()
    })
}