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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.google.gson.JsonObject
import es.verdnatura.domain.SalixCallback
import es.verdnatura.domain.SilexCallback
import es.verdnatura.domain.formatWithQuotes
import es.verdnatura.domain.model.Filter
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.ResponseItemMachineControl
import es.verdnatura.presentation.common.ResponseItemVO
import es.verdnatura.presentation.view.feature.controlvehiculo.fragment.model.DeviceId
import org.json.JSONObject
import retrofit2.Response

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

    private val _responseinsert by lazy { MutableLiveData<ResponseItemVO>() }
    val responseinsert: LiveData<ResponseItemVO>
        get() = _responseinsert

    private val _responsecontrol by lazy { MutableLiveData<ResponseItemVO>() }
    val responsecontrol: LiveData<ResponseItemVO>
        get() = _responsecontrol

    private val _responsemachine by lazy { MutableLiveData<ResponseItemMachineControl>() }
    val responsemachine: LiveData<ResponseItemMachineControl>
        get() = _responsemachine

    private val _responseGetExtensionFromUserId by lazy { MutableLiveData<ResponseItemVO>() }
    val responseGetExtensionFromUserId: LiveData<ResponseItemVO>
        get() = _responseGetExtensionFromUserId

    fun machineWorker_add(
        plateNumber: String
    ) {
        //tarea 6276 vehiculo
        //salix.machineWorkerUpdateInTime(plateNumber)
        silex.machineWorker_add(plateNumber)
            .enqueue(object : SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseinsert.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    //sergio_devuelve true o false

                    if (response.body().toString() == "false") {
                        _responseinsert.value = ResponseItemVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )

                    } else {
                        _responseinsert.value = ResponseItemVO(
                            isError = false,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this), response.message()
                            ),
                            response = response.body().toString()
                        )
                    }

                }

            })
    }

    fun machineWorker_update(
        plate: String
    ) {
        //Tarea 6276 //vehiculo
        //salix.machineWorkerUpdateInTime(plate)
        silex.machineWorker_update(plate)
            .enqueue(object : SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseinsert.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {

                    //sergio devuelve true o false

                    if (response.body().toString() == "false") {
                        _responseinsert.value = ResponseItemVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                    } else {

                        _responseinsert.value =
                            ResponseItemVO(isError = false, response = "")

                    }

                }

            })
    }

    fun workerMachineryIsRegistered(userId: Int) {
        salix.workerMachineryIsRegistered(arrayListOf(userId))
            .enqueue(object : SalixCallback<String>(context) {
                override fun onSuccess(response: Response<String>) {
                    _responsecontrol.value =
                        ResponseItemVO(isError = false, response = response.body()!!)
                }
            })
    }

    fun deviceProduction_getnameDevice(android_id: String) {

        salix.deviceProductionsGetName(
            Gson().toJson(
                Filter(
                    mapOf("id" to true),
                    mapOf("android_id" to mapOf("eq" to android_id))
                )
            )
        )
            .enqueue(object : SalixCallback<List<DeviceId>>(context) {
                override fun onError(t: Throwable) {
                    _responsemachine.value = ResponseItemMachineControl(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!),
                        type = ""
                    )
                }

                override fun onSuccess(response: Response<List<DeviceId>>) {
                    if (response.body() != null) {

                        _responsemachine.value =
                            ResponseItemMachineControl(
                                isError = false,
                                response = if (response.body()!!.isEmpty()) {
                                    ""
                                } else {
                                    response.body()!![0].id.toString()
                                },
                                type = "getnameDevice"
                            )
                    }

                }

            })
    }

    fun deviceProductionUserGetWorker(androidId: String) {
        salix.deviceProductionUserGetWorker(
            arrayListOf(
                androidId
            ).formatWithQuotes()
        ).enqueue(object : SalixCallback<List<JsonObject>>(context) {
            override fun onSuccess(response: Response<List<JsonObject>>) {
                _responsemachine.value =
                    ResponseItemMachineControl(
                        isError = false,
                        response = if (response.body()!!.isEmpty()) {
                            ""
                        } else {
                            (response.body()!![0].entrySet().first().value.toString()).replace(
                                "\"",
                                ""
                            )
                        },
                        type = "getWorker"
                    )
            }

            override fun onError(t: Throwable) {
                _responsemachine.value = ResponseItemMachineControl(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!),
                    type = ""
                )
            }
        })
    }

    fun machineGetWorkerPlate(userId: Int) {
        salix.machineGetWorkerPlate(
            arrayListOf(userId)
        ).enqueue(object : SalixCallback<List<JsonObject>>(context) {
            override fun onSuccess(response: Response<List<JsonObject>>) {
                var myArray = response.body()
                _responsemachine.value =
                    ResponseItemMachineControl(
                        isError = false,
                        response = if (myArray!!.isEmpty()) {
                            ""
                        } else {
                            myArray[0].entrySet().first().value.toString().replace("\"", "")
                        },
                        type = "getWorkerPlate"
                    )
            }

            override fun onError(t: Throwable) {
                _responsemachine.value = ResponseItemMachineControl(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!),
                    type = ""
                )
            }
        })
    }

    fun sip_getExtensionSalix(
        workerId: Int
    ) {
        salix.sip_getExtension(
            workerId
        ).enqueue(object : SalixCallback<Any>(context) {
            override fun onError(t: Throwable) {
                _responseGetExtensionFromUserId.value = ResponseItemVO(
                    isError = true,
                    errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                )
            }

            override fun onSuccess(response: Response<Any>) {

                if (response.body() != null) {
                    _responseGetExtensionFromUserId.value = ResponseItemVO(
                        isError = false,
                        response = JSONObject(response.body()!!.toString()).get("extension")
                            .toString(),
                        errorMessage = ""
                    )

                } else {
                    _responseGetExtensionFromUserId.value = ResponseItemVO(
                        isError = true,
                        response = "",
                        errorMessage = response.message()!!
                    )
                }
            }
        })
    }

}