package es.verdnatura.presentation.view.feature.historicoshelvinglog.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.historicoshelvinglog.model.ShelvingLogSalix
import es.verdnatura.presentation.view.feature.historicoshelvinglog.model.ShelvingLogSalixList
import retrofit2.Response


class shelvingLogViewModel(val context: Context) : BaseViewModel(context) {

    private val _itemShelvingLogSalixList by lazy { MutableLiveData<ShelvingLogSalixList>() }
    val loadShelvingLogSalixList = Transformations.map(_itemShelvingLogSalixList) { Event(it) }

    fun Shelvings(vShelvingFK: String) {
        salix.Shelvings(vShelvingFK).enqueue(object :
            SilexCallback<List<ShelvingLogSalix>>(context) {
            override fun onError(t: Throwable) {

                val listError: ArrayList<ShelvingLogSalix> = ArrayList()
                listError.add(
                    ShelvingLogSalix(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                )
                _itemShelvingLogSalixList.value = ShelvingLogSalixList(listError)
            }

            override fun onSuccess(response: Response<List<ShelvingLogSalix>>) {

                if (response.body() != null) {
                    _itemShelvingLogSalixList.value = response.body()?.let {
                        ShelvingLogSalixList(it)
                    }
                } else {
                    val listError: ArrayList<ShelvingLogSalix> = ArrayList()
                    listError.add(
                        ShelvingLogSalix(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                    )
                    _itemShelvingLogSalixList.value = ShelvingLogSalixList(listError)

                }

            }

        })

    }
}








