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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import es.verdnatura.domain.GetItemCardUserCase
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.historicoarticulo.model.ItemHistoricoListVO
import es.verdnatura.presentation.view.feature.historicoarticulo.model.ItemHistoricoVO
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HistoricoArticuloViewModel(context: Context) : BaseViewModel() {
    private val getItemCardUserCase: GetItemCardUserCase = GetItemCardUserCase(context)



    private val _historicoList by lazy { MutableLiveData<ItemHistoricoListVO>() }
    val historicoList: LiveData<ItemHistoricoListVO>
        get() = _historicoList


    val loadHistoricoList = Transformations.map(_historicoList) { Event(it) }


    fun itemDiary(usuario:String,password:String,itemFk:String,vWarehouseFk:String){
        getItemCardUserCase.itemDiary(usuario,password,itemFk,vWarehouseFk).enqueue(object :
            Callback<List<ItemHistoricoVO>> {
            override fun onFailure(call: Call<List<ItemHistoricoVO>>, t: Throwable) {
                val listError:ArrayList<ItemHistoricoVO> = ArrayList()
                listError.add(ItemHistoricoVO(isError = true,errorMessage =getMessageFromAllResponse(nameofFunction(this),t.message!!)))
                _historicoList.value = ItemHistoricoListVO(listError)
            }

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

        })
    }
}
