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 es.verdnatura.domain.GetInventaryUserCase
import es.verdnatura.domain.GetItemCardUserCase
import es.verdnatura.domain.GetWokerMistakeUSerCase
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.ItemInventaryVO
import es.verdnatura.presentation.view.feature.workermistake.model.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

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

    private val getInventaryUserCase: GetInventaryUserCase = GetInventaryUserCase(context)
    private val getItemCardUserCase: GetItemCardUserCase = GetItemCardUserCase(context)
    private val getWorkerMistakeUserCase: GetWokerMistakeUSerCase = GetWokerMistakeUSerCase(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 _buyersList by lazy { MutableLiveData<BuyerListVO>() }
    val buyersList: LiveData<BuyerListVO>
        get() = _buyersList

    //********************** a borrar, solo para montar fragment ****************/
    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

    //sergio para obtener comprador
    fun itemShelvingBuyerGet(user: String, password: String) {
        getInventaryUserCase.itemShelvingBuyerGet(user, password).enqueue(object :
            Callback<List<BuyerVO>> {
            override fun onFailure(call: Call<List<BuyerVO>>, t: Throwable) {
                val listError: ArrayList<BuyerVO> = ArrayList()
                listError.add(
                    BuyerVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                )
                _buyersList.value = BuyerListVO(listError)
            }

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

        })
    }


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

//sergio: borrar. En 6.1.3 ya no se utiliza
    /*fun getInventory(user:String,password:String,buyerFk:String){

        getInventaryUserCase.itemShelvingRadar(user,password,buyerFk).enqueue(object :
            Callback<List<ItemInventaryVO>> {
            override fun onFailure(call: Call<List<ItemInventaryVO>>, t: Throwable) {
                val listError:ArrayList<ItemInventaryVO> = ArrayList()
                listError.add(ItemInventaryVO(isError = true,errorMessage = t.message!!))
                _inventaryList.value = InventaryListVO(listError)
            }

            override fun onResponse(
                call: Call<List<ItemInventaryVO>>,
                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 = "Error en la llamada de itemShelvingRadar"))
                    _inventaryList.value = InventaryListVO(listError)

                }
            }

        })
    }*/

    fun getInventory(user: String, password: String, buyerFk: String, warehouseFk: String) {
        // getInventaryUserCase.itemShelvingRadar(user,password,buyerFk).enqueue(object :
        getInventaryUserCase.itemShelvingRadarFilterBuyer(user, password, buyerFk, warehouseFk)
            .enqueue(object :
                Callback<List<ItemInventaryVO>> {
                override fun onFailure(call: Call<List<ItemInventaryVO>>, t: Throwable) {
                    val listError: ArrayList<ItemInventaryVO> = ArrayList()
                    listError.add(
                        ItemInventaryVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _inventaryList.value = InventaryListVO(listError)
                }

                override fun onResponse(
                    call: Call<List<ItemInventaryVO>>,
                    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)

                    }
                }

            })
    }


    //sergio: se modifica por CAU a itemTrash
    fun itemTrash(
        itemFk: String,
        warehouseFk: String,
        user: String,
        password: String,
        newValue: String,
        isTrash: String
    ) {


        getItemCardUserCase.itemTrash(user, password, itemFk, warehouseFk, newValue, isTrash)
            .enqueue(object : Callback<Any> {


                override fun onFailure(call: Call<Any>, t: Throwable) {
                    _response.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onResponse(call: Call<Any>, response: Response<Any>) {
                    if (!response.isSuccessful) {
                        _response.value = ResponseItemVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                response.message()
                            )
                        )
                    } else {
                        _response.value =
                            ResponseItemVO(isError = false, response = response.message())
                    }

                }

            })
    }

    fun department_getHasMistakeSalix(token: String) {

        getWorkerMistakeUserCase.department_getHasMistakeSalix(token)

            .enqueue(object : Callback<List<DepartmentMistake>> {
                override fun onFailure(call: Call<List<DepartmentMistake>>, t: Throwable) {
                    val listError: ArrayList<DepartmentMistake> = ArrayList()
                    listError.add(
                        DepartmentMistake(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _mistakeDepartmentList.value = departmentMistakeList(listError)
                }

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

            })
    }

    fun department_getHasMistake(usuario: String, password: String) {

        getWorkerMistakeUserCase.department_getHasMistake(usuario, password)
            .enqueue(object : Callback<List<DepartmentMistake>> {
                override fun onFailure(call: Call<List<DepartmentMistake>>, t: Throwable) {
                    val listError: ArrayList<DepartmentMistake> = ArrayList()
                    listError.add(
                        DepartmentMistake(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _mistakeDepartmentList.value = departmentMistakeList(listError)
                }

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

            })
    }

    fun worker_getFromHasMistake(usuario: String, password: String, departmentFk: String) {
        getWorkerMistakeUserCase.worker_getFromHasMistake(usuario, password, departmentFk)
            .enqueue(object :
                Callback<List<WorkerFromMistake>> {
                override fun onFailure(call: Call<List<WorkerFromMistake>>, t: Throwable) {
                    val listError: ArrayList<WorkerFromMistake> = ArrayList()
                    listError.add(
                        WorkerFromMistake(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            )
                        )
                    )
                    _workerFromMistakeList.value = workerFromMistakeList(listError)
                }

                override fun onResponse(
                    call: Call<List<WorkerFromMistake>>,
                    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(usuario: String, password: String) {
        getWorkerMistakeUserCase.workerMistakeType_get(usuario, password)
            .enqueue(object : Callback<List<MistakeWorkerType>> {
                override fun onFailure(call: Call<List<MistakeWorkerType>>, t: Throwable) {
                    val listError: ArrayList<MistakeWorkerType> = ArrayList()
                    listError.add(
                        MistakeWorkerType(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(
                                nameofFunction(this),
                                t.message!!
                            ),
                            id = "0",
                            description = ""
                        )
                    )
                    _mistakeWorkerList.value = workerMistakeTypeList(listError)
                }

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

            })
    }

    fun workerMistake_Add(
        usuario: String,
        password: String,
        vUserFk: String,
        vTypeFk: String
    ) {
        getWorkerMistakeUserCase.workerMistake_Add(usuario, password, vUserFk, vTypeFk)
            .enqueue(object :
                Callback<Unit> {
                override fun onFailure(call: Call<Unit>, t: Throwable) {
                    _responseAddMistake.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

                override fun onResponse(
                    call: Call<Unit>,
                    response: Response<Unit>
                ) {
                    if (!response.isSuccessful) {

                        _responseAddMistake.value = ResponseItemVO(
                            isError = true,
                            errorMessage =
                                getMessageFromAllResponse(
                                    nameofFunction(this),
                                    response.message()
                                ), codeError = response.code())


                    } else {

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


}
