package es.verdnatura.presentation.view.feature.sacador.fragment.showticket

import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import es.verdnatura.domain.SalixCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.view.feature.collection.mapper.map
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.TicketStateList
import es.verdnatura.presentation.view.feature.sacador.model.TicketStateSalix
import retrofit2.Response

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

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

    private val _lastTicketList by lazy { MutableLiveData<TicketStateList>() }
    val lastTicketList: LiveData<TicketStateList> = _lastTicketList

    fun getSales(collectionFk: Int, print: Boolean, source: String) {

        salix.getSalesFromTicketOrCollection(collectionFk, print, source)
            .enqueue(object :
                SalixCallback<CollectionVO>(context) {

                override fun onSuccess(response: Response<CollectionVO>) {
                    _collectionTicketList.value = response.body()?.let { it.map(context) }
                }
            })
    }

    fun myLastTickets(userId: Int) {
        salix.myLastModified("""{"where": {"userFk": $userId}""")
            .enqueue(object : SalixCallback<List<TicketStateSalix>>(context) {
                @RequiresApi(Build.VERSION_CODES.O)
                override fun onSuccess(response: Response<List<TicketStateSalix>>) {
                    _lastTicketList.value = response.body()
                        ?.let { TicketStateList(it.sortedByDescending { it.created }) }
                }

            })
    }
}