package es.verdnatura.presentation.view.feature.precontrol

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
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.view.feature.collection.mapper.map
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import retrofit2.Response

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

    private val _collectionTicketList by lazy { MutableLiveData<CollectionVO>() }
    val collectionTicketList: LiveData<CollectionVO>
        get() = _collectionTicketList

    fun collectionTicketGet(collectionFk: Int, sectorFk: Int, print: String, type: String) {
        silex.collection_getTickets(collectionFk, sectorFk, print, type).enqueue(object :
            SilexCallback<CollectionVO>(context) {
            override fun onError(t: Throwable) {
                _collectionTicketList.value = CollectionVO(
                    0,
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<CollectionVO>) {
                if (response.body() != null) {
                    _collectionTicketList.value = response.body()?.let { it.map(context) }
                } else {
                    _collectionTicketList.value = CollectionVO(
                        0,
                        isError = true,
                        errorMessage = getMessageFromAllResponse(
                            nameofFunction(this),
                            response.message()
                        )
                    )
                }
            }
        })
    }

}