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.ImageResultModel
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
import com.pengxh.kt.lite.vm.LoadState
import java.io.File

class UploadFileViewModel : BaseViewModel() {

    private val gson by lazy { Gson() }
    val resultModel = MutableLiveData<ImageResultModel>()

    fun uploadImage(image: File) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.uploadImage(image)
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            loadState.value = LoadState.Success
            resultModel.value = gson.fromJson<ImageResultModel>(
                response, object : TypeToken<ImageResultModel>() {}.type
            )
        } else {
            loadState.value = LoadState.Fail
            response.toErrorMessage().show(BaseApplication.obtainInstance())
        }
    }, {
        loadState.value = LoadState.Fail
        it.printStackTrace()
    })
}