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

//import es.verdnatura.presentation.view.feature.paletizador.model.itemExpeditionDynamicsList
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
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: Int) {
        salix.expedition_getState(params = arrayListOf(expeditionFk))
            .enqueue(object : SalixCallback<ArrayList<JsonObject>>(context) {
                @RequiresApi(Build.VERSION_CODES.O)
                override fun onSuccess(response: Response<ArrayList<JsonObject>>) {
                    _itemexpedition.value = itemExpedetionState(
                        isError = false,
                        errorMessage = "",
                        list = if (response.body()!!.size > 0) {
                            getListFromJSON(response.body()!![0].asJsonObject)
                        } else {
                            mutableListOf()
                        }
                    )

                }

            })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getListFromJSON(json: JsonObject): MutableList<itemsExpeditionDynamics> {
        val gson = Gson()
        var list = mutableListOf<itemsExpeditionDynamics>()
        var 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
    }
}








