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

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.google.gson.JsonObject
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.domain.SalixCallback
import es.verdnatura.domain.SilexCallback
import es.verdnatura.presentation.base.BaseViewModel
import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.Event
import es.verdnatura.presentation.common.ResponseItemVO
import es.verdnatura.presentation.view.feature.calidad.model.BuyerListVO
import es.verdnatura.presentation.view.feature.calidad.model.BuyerVO
import es.verdnatura.presentation.view.feature.inventario.model.InventaryListVO
import es.verdnatura.presentation.view.feature.inventario.model.InventoryParkingList
import es.verdnatura.presentation.view.feature.inventario.model.ItemInventaryVO
import es.verdnatura.presentation.view.feature.inventario.model.ItemInventoryParking
import es.verdnatura.presentation.view.feature.workermistake.model.DepartmentMistake
import es.verdnatura.presentation.view.feature.workermistake.model.ExpeditionMistakeSalix
import es.verdnatura.presentation.view.feature.workermistake.model.MistakeType
import es.verdnatura.presentation.view.feature.workermistake.model.WorkerFromMistake
import es.verdnatura.presentation.view.feature.workermistake.model.WorkerMistakeSalix
import es.verdnatura.presentation.view.feature.workermistake.model.departmentMistakeList
import es.verdnatura.presentation.view.feature.workermistake.model.workerFromMistakeList
import es.verdnatura.presentation.view.feature.workermistake.model.workerMistakeTypeList
import retrofit2.Response

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

    private val _inventaryList by lazy { MutableLiveData<InventaryListVO>() }
    val inventaryList: LiveData<InventaryListVO>
        get() = _inventaryList

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

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

    private val _buyersList by lazy { MutableLiveData<BuyerListVO>() }
    val buyersList: LiveData<BuyerListVO>
        get() = _buyersList

    private val _mistakeDepartmentList by lazy { MutableLiveData<departmentMistakeList>() }
    val mistakeDepartmentList: LiveData<departmentMistakeList>
        get() = _mistakeDepartmentList

    private val _workerFromMistakeList by lazy { MutableLiveData<workerFromMistakeList>() }
    val workerFromMistakeList: LiveData<workerFromMistakeList>
        get() = _workerFromMistakeList

    private val _mistakeWorkerList by lazy { MutableLiveData<workerMistakeTypeList>() }
    val mistakeWorkerList: LiveData<workerMistakeTypeList>
        get() = _mistakeWorkerList

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


    private val _inventoryListParking by lazy { MutableLiveData<InventoryParkingList>() }
    val inventoryListParking: LiveData<InventoryParkingList>
        get() = _inventoryListParking

    val loadInventaryParkingList = Transformations.map(_inventoryListParking) { Event(it) }


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

    val loadReponseCode = Transformations.map(_responseCode) { Event(it) }

    //sergio para obtener comprador
    fun itemShelvingBuyerGet() {
        salix.getBuyers().enqueue(object :
            SilexCallback<List<BuyerVO>>(context) {
            override fun onError(t: Throwable) {
                val listError: ArrayList<BuyerVO> = ArrayList()
                listError.add(
                    BuyerVO(0,"",
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                )
                _buyersList.value = BuyerListVO(listError)
            }

            override fun onSuccess(response: Response<List<BuyerVO>>) {
                if (response.body() != null) {
                    _buyersList.value = response.body()?.let { BuyerListVO(it) }
                } else {
                    val listError: ArrayList<BuyerVO> = ArrayList()
                    listError.add(
                        BuyerVO(0,"",
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                    )
                    _buyersList.value = BuyerListVO(listError)
                }
            }

        })
    }


    val loadInventaryList = Transformations.map(_inventaryList) { Event(it) }

    fun getInventory(buyerFk: Int, warehouseFk: Int) {
        silex.itemShelvingRadarFilterBuyer(buyerFk, warehouseFk)
            .enqueue(object :
                SilexCallback<List<ItemInventaryVO>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<ItemInventaryVO> = ArrayList()
                    listError.add(
                        ItemInventaryVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _inventaryList.value = InventaryListVO(listError)
                }

                override fun onSuccess(response: Response<List<ItemInventaryVO>>) {
                    if (response.body() != null) {
                        _inventaryList.value = response.body()?.let { InventaryListVO(it) }
                    } else {
                        val listError: ArrayList<ItemInventaryVO> = ArrayList()
                        listError.add(
                            ItemInventaryVO(
                                isError = true,
                                errorMessage = getMessageFromAllResponse(
                                    nameofFunction(this),
                                    response.message()
                                )
                            )
                        )
                        _inventaryList.value = InventaryListVO(listError)

                    }
                }

            })
    }

    fun itemShelvingUpdate(
        itemShelvingFk: Long,
        params: Any,

        ) {


        salix.itemShelvingUpdate(itemShelvingFk, params)
            .enqueue(object : SilexCallback<Any>(context) {

                override fun onError(t: Throwable) {
                    _response.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    _response.value =
                        ResponseItemVO(isError = false, response = response.message())
                }

            })
    }

    fun itemShelvingsReset(
        where: JsonObject,
        params: Any,

        ) {


        salix.itemShelvingsUpdate(where, params)
            .enqueue(object : SilexCallback<Any>(context) {

                override fun onError(t: Throwable) {
                    _responseReset.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    _responseReset.value =
                        ResponseItemVO(isError = false, response = response.message())
                }

            })
    }

    fun itemTrash(
        itemFk: Int,
        warehouseFk: Int,
        newValue: Int,
        isTrash: Boolean
    ) {


        silex.itemTrash(itemFk, warehouseFk, newValue, isTrash)
            .enqueue(object : SilexCallback<Any>(context) {

                override fun onError(t: Throwable) {
                    _response.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    _response.value =
                        ResponseItemVO(isError = false, response = response.message())
                }

            })
    }


    fun department_getHasMistake() {

        salix.department_getHasMistake()
            .enqueue(object : SalixCallback<List<DepartmentMistake>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<DepartmentMistake> = ArrayList()
                    listError.add(
                        DepartmentMistake(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _mistakeDepartmentList.value = departmentMistakeList(listError)
                }

                override fun onSuccess(response: Response<List<DepartmentMistake>>) {
                    if (response.body() != null) {
                        _mistakeDepartmentList.value =
                            response.body()?.let { departmentMistakeList(it) }
                    } else {
                        val listError: ArrayList<DepartmentMistake> = ArrayList()
                        listError.add(DepartmentMistake())
                        _mistakeDepartmentList.value = departmentMistakeList(listError)
                    }
                }

            })
    }

    fun worker_getFromHasMistake(departmentFk: Int) {
        silex.worker_getFromHasMistake(departmentFk)
            .enqueue(object :
                SilexCallback<List<WorkerFromMistake>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<WorkerFromMistake> = ArrayList()
                    listError.add(
                        WorkerFromMistake(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _workerFromMistakeList.value = workerFromMistakeList(listError)
                }

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

                        _workerFromMistakeList.value =
                            response.body()?.let { workerFromMistakeList(it) }
                    } else {
                        val listError: ArrayList<WorkerFromMistake> = ArrayList()
                        listError.add(
                            WorkerFromMistake(
                                isError = true,
                                errorMessage = getMessageFromAllResponse(
                                    nameofFunction(this),
                                    response.message()
                                )
                            )
                        )
                        _workerFromMistakeList.value = workerFromMistakeList(listError)
                    }
                }

            })
    }

    fun workerMistakeType_get() {
        //Tarea 5134
        salix.workerMistakesTypes()
            .enqueue(object : SilexCallback<List<MistakeType>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<MistakeType> = ArrayList()
                    listError.add(
                        MistakeType(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            ),
                            description = ""
                        )
                    )
                    _mistakeWorkerList.value = workerMistakeTypeList(listError)
                }

                override fun onSuccess(response: Response<List<MistakeType>>) {
                    if (response.body() != null) {
                        _mistakeWorkerList.value =
                            response.body()?.let { workerMistakeTypeList(it) }
                    } else {
                        val listError: ArrayList<MistakeType> = ArrayList()
                        listError.add(
                            MistakeType(
                                isError = true,
                                errorMessage = getMessageFromAllResponse(
                                    nameofFunction(this),
                                    response.message()
                                ),
                                description = ""
                            )
                        )
                        _mistakeWorkerList.value = workerMistakeTypeList(listError)
                    }
                }

            })
    }


    fun workerMistake_Add(

        vUserFk: Int,
        vTypeFk: String
    ) {
        //Tarea 5134
        salix.workerMistakesAdd(WorkerMistakeSalix(vUserFk,vTypeFk))
            .enqueue(object :
                SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseAddMistake.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<Any>) {
                    // sergio:refactor:solo debería haber un mensaje no un response o errorMessage
                    _responseAddMistake.value =
                        ResponseItemVO(
                            isError = false,
                            response = response.message()
                        )

                }
            })
    }

    fun expeditionMistake_add(
        vExpeditionFk: Int,
        vTypeFk: String,
    ) {
        //Tarea 5134
        salix.expeditionMistakesAdd(
            ExpeditionMistakeSalix(expeditionFk = vExpeditionFk, typeFk = vTypeFk, workerFk = (context as MobileApplication).userId!!))
            .enqueue(object :
                SalixCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseAddMistake.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

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

                    // sergio:refactor:solo debería haber un mensaje no un response o errorMessage
                    _responseAddMistake.value =
                        ResponseItemVO(
                            isError = false,
                            response = response.message()
                        )
                }
            })
    }

    fun getInventoryParking(
        vParkingFrom: String,
        vParkingTo: String
    ) {

        salix.getInventoryParking(vParkingFrom, vParkingTo)
            .enqueue(object :
                SilexCallback<List<ItemInventoryParking>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<ItemInventoryParking> = ArrayList()
                    listError.add(
                        ItemInventoryParking(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            ),
                        )
                    )
                    _inventoryListParking.value = InventoryParkingList(listError)

                }

                override fun onSuccess(response: Response<List<ItemInventoryParking>>) {

                    if (response.body() != null) {
                        _inventoryListParking.value =
                            response.body()?.let { InventoryParkingList(it) }

                    }else{
                        val listError: ArrayList<ItemInventoryParking> = ArrayList()
                        listError.add(
                            ItemInventoryParking(
                                isError = false,
                                errorMessage = getMessageFromAllResponse(
                                    nameofFunction(this),
                                   response.message()
                                ),
                            )
                        )
                        _inventoryListParking.value = InventoryParkingList(listError)
                    }
                }

            })
    }

    fun ItemListInventoryParking_(
        vParkingFrom: String,
        vParkingTo: String
    ) {

        var myList = InventoryParkingList(
            listOf(
                ItemInventoryParking(
                    1,
                    31,
                    vParkingFrom,
                    vParkingTo,
                    19897,
                    "Dendrobium Galaxy",
                    510,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/dgalaxy",
                    0,
                    2
                ),
                ItemInventoryParking(
                    2,
                    31,
                    "F-01-1",
                    "OZR",
                    92400,
                    "Cymbidium Avalanche",
                    14,
                    37,
                    "Sergio de la Torre Nebot",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/92400",
                    1,
                    2
                ),
                ItemInventoryParking(
                    3,
                    31,
                    "F-01-1",
                    "OZR",
                    92400,
                    "Cymbidium Avalanche",
                    2,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/92400",
                    null,
                    2
                ),
                ItemInventoryParking(
                    4,
                    32,
                    "F-01-2",
                    "PLY",
                    19897,
                    "Dendrobium Galaxy",
                    520,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/dgalaxy",
                    0,
                    2
                ),
                ItemInventoryParking(
                    5,
                    33,
                    "F-01-3",
                    "ZLZ",
                    2912,
                    "HEL Tropical Red",
                    2,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/002912",
                    0,
                    0
                ),
                ItemInventoryParking(
                    6,
                    34,
                    "F-01-4",
                    "JXU",
                    25942,
                    "HEL BQ Amor (x bouquet)",
                    0,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/bqamor",
                    2,
                    0
                ),
                ItemInventoryParking(
                    7,
                    34,
                    "F-01-4",
                    "MUU",
                    25942,
                    "HEL BQ Amor (x bouquet)",
                    5,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/bqamor",
                    0,
                    0
                ),
                ItemInventoryParking(
                    8,
                    34,
                    "F-01-4",
                    "JXU",
                    50001,
                    "Monstera I",
                    130,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/50001",
                    0,
                    2
                ),
                ItemInventoryParking(
                    9,
                    34,
                    "F-01-4",
                    "JXU",
                    50004,
                    "Monstera IV",
                    240,
                    37,
                    "Jose Alarcan Gomex",
                    "http://verdnatura.es/vn-image-data/catalog/1600x900/50003",
                    0,
                    2
                )
            )
        )
     //   _inventoryListParking.value = myList

        /*silex.itemShelving_inventory(vParkingFromFk, vParkingToFk)
            .enqueue(object :
                SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _responseAddMistake.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

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

                    // sergio:refactor:solo debería haber un mensaje no un response o errorMessage
                    _responseAddMistake.value =
                        ResponseItemVO(
                            isError = false,
                            response = response.message()
                        )
                }
            })*/
    }

    fun expeditionMistakeType_get() {
        // Tarea 5134 pasar a salix
        salix.getExpeditionMistakeTypes()
            .enqueue(object : SalixCallback<List<MistakeType>>(context) {
                override fun onError(t: Throwable) {
                    val listError: ArrayList<MistakeType> = ArrayList()
                    listError.add(
                        MistakeType(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            ),
                            description = ""
                        )
                    )
                    _mistakeWorkerList.value = workerMistakeTypeList(listError)
                }

                override fun onSuccess(response: Response<List<MistakeType>>) {

                    if (response.body() != null) {
                        _mistakeWorkerList.value =
                            response.body()?.let { workerMistakeTypeList(it) }
                    } else {
                        val listError: ArrayList<MistakeType> = ArrayList()
                        listError.add(
                            MistakeType(
                                isError = true,
                                errorMessage = getMessageFromAllResponse(
                                    nameofFunction(this),
                                    response.message()
                                ),
                                description = ""
                            )
                        )
                        _mistakeWorkerList.value = workerMistakeTypeList(listError)
                    }
                }

            })
    }

    fun getIdFromCodeSalix(code: String) {
        salix.barcodes_toitem(code)
            .enqueue(object : SilexCallback<String?>(context) {
                override fun onError(t: Throwable) {
                    _responseCode.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onSuccess(response: Response<String?>) {
                    if (response.body() == null) {
                        _responseCode.value = ResponseItemVO(
                            isError = true,
                            errorMessage = context.getString(R.string.itemNotValid)
                        )
                    } else {
                        println("itemCode response"+response.body())
                        println("itemCode response string"+response.body().toString())
                        println("itemCode response toInt"+response.body().toString().toInt())

                        _responseCode.value =
                            ResponseItemVO(isError = false, response = response.body()!!.toString())
                    }

                }
            })
    }
}
