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

//import es.verdnatura.presentation.view.feature.paletizador.model.itemExpeditionDynamicsList
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import es.verdnatura.domain.SalixCallback
import es.verdnatura.domain.isoToString
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpedetionState
import es.verdnatura.presentation.view.feature.paletizador.model.ItemsExpeditionDynamics
import retrofit2.Response

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

    private val _itemExpedition by lazy { MutableLiveData<ItemExpedetionState>() }
    val itemExpedition: LiveData<ItemExpedetionState>
        get() = _itemExpedition

    fun expeditionGetStateJSON(expeditionFk: Long) {
        salix.expeditionGetState(params = arrayListOf(expeditionFk))
            .enqueue(object : SalixCallback<ArrayList<JsonObject>>(context) {
                override fun onSuccess(response: Response<ArrayList<JsonObject>>) {
                    _itemExpedition.value = ItemExpedetionState(

                        list = if (response.body()!!.size > 0) {
                            getListFromJSON(response.body()!![0].asJsonObject)
                        } else {
                            mutableListOf()
                        }
                    )

                }

            })
    }

    fun getListFromJSON(json: JsonObject): MutableList<ItemsExpeditionDynamics> {
        val gson = Gson()
        val list = mutableListOf<ItemsExpeditionDynamics>()
        val expeditionState: Map<String, String?> =
            gson.fromJson(json, object : TypeToken<Map<String, String?>>() {}.type)
        expeditionState.forEach {
            list.add(ItemsExpeditionDynamics(key = it.key, it.value ?: ""))
        }
        list.forEach { element ->
            if (element.value!!.takeLast(4).matches(Regex("[0-9]{3}Z"))) {
                element.value = element.value.isoToString(false)
            }
        }

        return list
    }
}








