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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import es.verdnatura.domain.ConstAndValues.LIMITRECORDSSHELVINGLOG
import es.verdnatura.domain.SalixCallback
import es.verdnatura.domain.userCases.GetItemFromBarcodeUseCase
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.view.feature.historicoshelving.model.ItemShelvingLog
import es.verdnatura.presentation.view.feature.historicoshelving.model.ItemShelvingLogList
import retrofit2.Response

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

    private val getItemFromBarcodeUseCase =  GetItemFromBarcodeUseCase(salix)

    private val _itemShelvingLogList by lazy { MutableLiveData<ItemShelvingLogList>() }
    val itemShelvingLogList: LiveData<ItemShelvingLogList> = _itemShelvingLogList

    private val _responseCode by lazy { MutableLiveData<Int?>() }
    val responseCode: LiveData<Int?> = _responseCode

    fun itemShelvingLogGet(shelvingOrItem: String, records: Int = LIMITRECORDSSHELVINGLOG) {
        //tarea 7168
        salix.itemShelvingLogGet(
            filter = """{ "where": { "or": [ {"shelvingFk": "$shelvingOrItem"}, {"itemFk": "$shelvingOrItem"} ] }, 
                "limit": $records, 
                "order": "created DESC", 
                "include": [ { "relation": "worker", "scope": { "fields": ["code"]} }, 
                { "relation": "item", "scope": { "fields": ["longName"] } } ] }
""".trim()
        )
            .enqueue(object :
                SalixCallback<List<ItemShelvingLog>>(context) {
                override fun onSuccess(response: Response<List<ItemShelvingLog>>) {
                    _itemShelvingLogList.value = response.body()?.let {
                        ItemShelvingLogList(it)
                    }
                }

            })
    }

    fun getIdFromCodeSalix(code: String, records: Int) {
        getItemFromBarcodeUseCase.execute (code)
            .enqueue(object : SalixCallback<Int?>(context) {

                override fun onSuccess(response: Response<Int?>) {
                    itemShelvingLogGet(response.body()!!.toString(), records)

                }
            })
    }

}








