package es.verdnatura.presentation.view.feature.qr


import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import es.verdnatura.R
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.ResponseItemVO
import retrofit2.Response

class QrFragmentViewModel(var context: Context) : BaseViewModel(context) {

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


    fun qr_getCall(vStatement: String) {
        silex.qr_getCall(vStatement)
            .enqueue(object : SilexCallback<Any>(context) {
                override fun onError(t: Throwable) {
                    _qrresponse.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this), t.message!!)
                    )
                }

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

                    if (response.raw().code() == 555 || response.raw().code() == 403) {

                        _qrresponse.value = ResponseItemVO(
                            response = "",
                            isError = true,
                            errorMessage = context.getString(
                                R.string.userNotPermission
                            )
                        )

                    } else if (response.body() != null) {
                        _qrresponse.value = ResponseItemVO(
                            response = response.body().toString(),
                            isError = false,
                            errorMessage = ""
                        )

                    } else {

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


                    }
                }

            })
    }
}



