package es.verdnatura.presentation.view.feature.historicovehiculo.fragment

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import es.verdnatura.domain.SilexCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.Event
import es.verdnatura.presentation.view.feature.historicovehiculo.model.ItemHistoricoVehiculo
import es.verdnatura.presentation.view.feature.historicovehiculo.model.ItemHistoricoVehiculoList
import retrofit2.Response

class HistoricoVehiculoViewModel(var context: Context) : BaseViewModel(context) {

    private val _historicovehiculoList by lazy { MutableLiveData<ItemHistoricoVehiculoList>() }
    val loadHistoricoVehiculoList = Transformations.map(_historicovehiculoList) { Event(it) }

    fun machineWorker_getHistorical(plateNumber: String) {
        silex.machineWorker_getHistorical(plateNumber).enqueue(object :
            SilexCallback<List<ItemHistoricoVehiculo>>(context) {
            override fun onError(t: Throwable) {
                val listError: ArrayList<ItemHistoricoVehiculo> = ArrayList()
                listError.add(
                    ItemHistoricoVehiculo(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                )
                _historicovehiculoList.value = ItemHistoricoVehiculoList(listError)
            }

            override fun onSuccess(response: Response<List<ItemHistoricoVehiculo>>) {
                if (response.body() != null) {
                    _historicovehiculoList.value =
                        response.body()?.let { ItemHistoricoVehiculoList(it) }
                } else {
                    val listError: ArrayList<ItemHistoricoVehiculo> = ArrayList()
                    listError.add(
                        ItemHistoricoVehiculo(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                    )
                    _historicovehiculoList.value = ItemHistoricoVehiculoList(listError)

                }

            }

        })
    }
}
