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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import es.verdnatura.domain.SalixCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.common.Event
import es.verdnatura.presentation.view.feature.paletizador.model.ExpeditionTruckSalix
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckList
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import retrofit2.Call
import retrofit2.Response
import java.time.LocalDate
import java.time.LocalTime

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

    private val _expeditionTruckList by lazy { MutableLiveData<ItemExpeditionTruckList>() }
    val loadExpeditionTruckList: LiveData<Event<ItemExpeditionTruckList>> =
        _expeditionTruckList.map { Event(it) }

    fun expeditionTruckList() {
        salix.roadMapStopGet(
            """{"where": { "eta": {
        "between": ["${LocalDate.now().atTime(LocalTime.MIN)}", 
        "${
                LocalDate.now().atTime(LocalTime.MAX)
            }"]}},"order": "eta ASC"}"""
        ).enqueue(object : SalixCallback<List<ItemExpeditionTruckVO>>(context) {
            override fun onSuccess(response: Response<List<ItemExpeditionTruckVO>>) {
                _expeditionTruckList.value = response.body()?.let { ItemExpeditionTruckList(it) }
            }
        })
    }

    fun roadMapStopAdd(vHour: String, vDescription: String) {
        salix.roadMapStopAdd(
            ExpeditionTruckSalix(
                eta = "${LocalDate.now()} $vHour", description = vDescription
            )
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onResponse(call: Call<Any>, response: Response<Any>) {
                expeditionTruckList()
            }

        })
    }

}
