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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import es.verdnatura.domain.GetBuscarItemUserCase
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.buscaritem.model.ItemLocationVO
import es.verdnatura.presentation.view.feature.buscaritem.model.LocationListVO
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class BuscarItemViewModel(context: Context) : BaseViewModel() {
    private val getBuscarItemUserCase: GetBuscarItemUserCase = GetBuscarItemUserCase(context)


    private val _locationList by lazy { MutableLiveData<LocationListVO>() }
    val locationList: LiveData<LocationListVO>
        get() = _locationList


    val loadLocationList = Transformations.map(_locationList) { Event(it) }


    fun getLocations(user:String,password:String,itemFk:String){
        getBuscarItemUserCase.searchItemsUbicador(user,password,itemFk).enqueue(object : Callback<List<ItemLocationVO>> {
            override fun onFailure(call: Call<List<ItemLocationVO>>, t: Throwable) {
                val listError:ArrayList<ItemLocationVO> = ArrayList()
                listError.add(ItemLocationVO(isError = true,errorMessage =getMessageFromAllResponse(nameofFunction(this),t.message!!)))
                _locationList.value = LocationListVO(listError)
            }

            override fun onResponse(
                call: Call<List<ItemLocationVO>>,
                response: Response<List<ItemLocationVO>>
            ) {
                if (response.body() != null){
                    _locationList.value = response.body()?.let { LocationListVO(it) }
                }else{
                    val listError:ArrayList<ItemLocationVO> = ArrayList()
                    listError.add(ItemLocationVO(isError = true,errorMessage = getMessageFromAllResponse(nameofFunction(this),response.message())))
                    _locationList.value = LocationListVO(listError)
                }
            }

        })
    }

}
