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


import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import es.verdnatura.domain.GetSacadorControladorUserCase
import es.verdnatura.domain.GetSmarttagsUserCase
import es.verdnatura.presentation.base.BaseViewModel

import es.verdnatura.presentation.base.getMessageFromAllResponse
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.common.ResponseItemVO
import es.verdnatura.presentation.view.feature.collection.mapper.map
import es.verdnatura.presentation.view.feature.sacador.mapper.toDateFormat
import es.verdnatura.presentation.view.feature.sacador.model.CollectionListVO
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.smarttag.sacador.model.SmartTagRegister
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

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

    //val emptyMessage = "No tienes colecciones pendientes. Presiona sobre el + para crear colección"

    private val contextApp=context
    private val getSacadorControladorUserCase: GetSacadorControladorUserCase = GetSacadorControladorUserCase(
        context
    )

    private val GetSmarttagsUserCase: GetSmarttagsUserCase = GetSmarttagsUserCase(
        context
    )

    private val _collectionList by lazy { MutableLiveData<CollectionListVO>() }
    val collectionList: LiveData<CollectionListVO>
        get() = _collectionList

    private val _collectionTicketList by lazy { MutableLiveData<CollectionVO>() }
    val collectionTicketList: LiveData<CollectionVO>
        get() = _collectionTicketList

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

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


    private val _registerSmarttagInsert by lazy { MutableLiveData<SmartTagRegister>() }
    val registerSmarttagInsert: LiveData<SmartTagRegister>
        get() = _registerSmarttagInsert


    fun collectionTicketGet(
        usuario: String,
        password: String,
        collectionFk: String,
        sectorFk: String,
        print: String,
        type:String
    ){
        getSacadorControladorUserCase.collectionTicketGet(
            usuario,
            password,
            collectionFk,
            sectorFk,
            print,
            type
        ).enqueue(object :
            Callback<CollectionVO> {
            override fun onFailure(call: Call<CollectionVO>, t: Throwable) {
                _collectionTicketList.value = CollectionVO(
                    isError = true,
                    errorMessage =getMessageFromAllResponse(nameofFunction(this),t.message!!)
                )
            }

            override fun onResponse(
                call: Call<CollectionVO>,
                response: Response<CollectionVO>
            ) {
                if (response.body() != null) {
                    _collectionTicketList.value = response.body()?.let { it.map(contextApp) }
                } else {
                    _collectionTicketList.value = CollectionVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this),response.message())
                    )
                }
            }
        })
    }

         fun collectionNew(usuario: String, password: String, sectorFk: String, wagons: String){
            getSacadorControladorUserCase.collectionNew(usuario, password, sectorFk, wagons).enqueue(
                object :
                    Callback<String> {
                    override fun onFailure(call: Call<String>, t: Throwable) {
                        _response.value =
                            ResponseItemVO(isError = true, errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!))


                    }

                    override fun onResponse(
                        call: Call<String>,
                        response: Response<String>
                    ) {
                        if (response.body() != null) {
                            _response.value =
                                ResponseItemVO(isError = false, response = response.body()!!)
                        } else {

                            _response.value = ResponseItemVO(
                                isError = true,
                                errorMessage = getMessageFromAllResponse(nameofFunction(this),response.message())
                            )

                        }
                    }
                })
    }


    fun collection_assign(usuario: String, password: String){
        getSacadorControladorUserCase.collection_assign(usuario, password).enqueue(
            object :
                Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {
                    _response.value =
                        ResponseItemVO(isError = true, errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!))


                }

                override fun onResponse(
                    call: Call<String>,
                    response: Response<String>
                ) {
                    if (response.body() != null) {
                        _response.value =
                            ResponseItemVO(isError = false, response = response.body()!!)
                    } else {

                        _response.value = ResponseItemVO(
                            isError = true,
                            errorMessage = getMessageFromAllResponse(nameofFunction(this),response.message())
                        )

                    }
                }
            })
    }

    fun collection_new_smart(usuario: String, password: String, sectorFk: String, wagons: String,tagtype:String){
        getSacadorControladorUserCase.collectionNewSmarttag(usuario, password, sectorFk, wagons,tagtype).enqueue(
            object :
                Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {
                    _responseCollectionSmart.value =
                        ResponseItemVO(isError = true, errorMessage =  getMessageFromAllResponse(nameofFunction(this),t.message!!))

                }

                override fun onResponse(
                    call: Call<String>,
                    response: Response<String>
                ) {
                    if (response.body() != null) {

                        _responseCollectionSmart.value =
                            ResponseItemVO(isError = false, response = response.body()!!)
                    } else {
                        _responseCollectionSmart.value = ResponseItemVO(
                            isError = true,
                            errorMessage =  getMessageFromAllResponse(nameofFunction(this),response.message())
                        )

                    }
                }
            })
    }

   /* fun collection_new_smarttag(usuario: String, password: String, sectorFk: String, wagons: String,tagtype:String){
        getSacadorControladorUserCase.collectionNewSmarttag(usuario, password, sectorFk, wagons,tagtype).enqueue(
            object :
                Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {
                     _responseCollectionSmarttag.value =
                        ResponseItemVO(isError = true, errorMessage =  getMessageFromAllResponse(nameofFunction(this),t.message!!))
                    Log.d("VERDNATURA::","onFAilure")

                }

                override fun onResponse(
                    call: Call<String>,
                    response: Response<String>
                ) {
                    if (response.body() != null) {

                        Log.d("VERDNATURA::","La coleccion de collectionNew_SMARTGS es "+response.body())
                         _responseCollectionSmarttag.value =
                            ResponseItemVO(isError = false, response = response.body()!!)
                    } else {
                        Log.d("VERDNATURA::","Else del response.body() ")
                        _responseCollectionSmarttag.value =
                            ResponseItemVO(
                            isError = true,
                            errorMessage =  getMessageFromAllResponse(nameofFunction(this),response.message())
                        )

                    }
                }
            })
    }*/

    fun collectionGet(usuario: String, password: String){
        //////Log.i("VERDNATURA:","collectionGet para coger tickets")
        getSacadorControladorUserCase.collectionGet(usuario, password).enqueue(object :
            Callback<List<CollectionVO>> {
            override fun onFailure(call: Call<List<CollectionVO>>, t: Throwable) {
                val listError: ArrayList<CollectionVO> = ArrayList()
                listError.add(CollectionVO(isError = true, errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!)))
                _collectionList.value = CollectionListVO(listError)
            }


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

                }
            }

        })
    }

    fun collectionGetSalix(token:String){
        getSacadorControladorUserCase.collectionGetSalix(token).enqueue(object :
            Callback<List<CollectionVO>> {
            override fun onFailure(call: Call<List<CollectionVO>>, t: Throwable) {
                val listError: ArrayList<CollectionVO> = ArrayList()
                listError.add(CollectionVO(isError = true, errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!)))
                _collectionList.value = CollectionListVO(listError)
            }


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

                }
            }

        })
    }


    fun smartTagInsertTicket(collectionFk: String)
    {
        GetSmarttagsUserCase.smartTagInsertTicket(collectionFk)
            .enqueue(object : Callback<SmartTagRegister>
            {
                override fun onResponse(
                    call: Call<SmartTagRegister>,
                    response: Response<SmartTagRegister>
                )
                {

                    val responseSmart: SmartTagRegister

                    if (response.isSuccessful){
                        responseSmart = SmartTagRegister(
                            message="",
                            isError = false,
                            errorMessage = ""
                        )

                    }else{
                        var text = JSONObject(response.errorBody()!!.string()).get("error")
                        var message = JSONObject(text.toString()).get("message")

                        responseSmart = SmartTagRegister(
                            isError = true,
                            errorMessage = message.toString()
                        )
                    }


                    _registerSmarttagInsert.value = responseSmart
                }

                override fun onFailure(call: Call<SmartTagRegister>, t: Throwable)
                {
                    val responseSmart =
                        SmartTagRegister(isError = true, errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!))

                    _registerSmarttagInsert.value = responseSmart
                }

            })
    }



}
