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

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import es.verdnatura.domain.GetVehicleControlTimeUserCase
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.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber.d
import timber.log.Timber.i

class HistoricoVehiculoViewModel (context: Context) : BaseViewModel() {
    private val GetVehicleControlTimeUserCase: GetVehicleControlTimeUserCase = GetVehicleControlTimeUserCase(context)


    private val _historicovehiculoList by lazy { MutableLiveData<ItemHistoricoVehiculoList>() }


    val loadHistoricoVehiculoList = Transformations.map(_historicovehiculoList) { Event(it) }


    fun machineWorker_getHistorical(usuario:String,password:String,plateNumber:String){
        GetVehicleControlTimeUserCase.machineWorker_getHistorical(usuario,password,plateNumber).enqueue(object :
            Callback<List<ItemHistoricoVehiculo>> {
            override fun onFailure(call: Call<List<ItemHistoricoVehiculo>>, t: Throwable) {
                val listError:ArrayList<ItemHistoricoVehiculo> = ArrayList()
                listError.add(ItemHistoricoVehiculo(isError = true,errorMessage =getMessageFromAllResponse(nameofFunction(this),t.message!!)))
                _historicovehiculoList.value = ItemHistoricoVehiculoList(listError)

            }

            override fun onResponse(
                call: Call<List<ItemHistoricoVehiculo>>,
                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)

                }

            }

        })
    }
}
