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.GetQrReaderUserCase
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.Call
import retrofit2.Callback
import retrofit2.Response

class QrFragmentViewModel(context: Context) : BaseViewModel() {
    private val contextApp =context
    private val GetQrReaderUserCase: GetQrReaderUserCase =
        GetQrReaderUserCase(context)


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


    fun qr_getCall(user: String, password: String, vStatement: String){
        GetQrReaderUserCase.qr_getCall(user, password, vStatement)
            .enqueue(object : Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {

                    _qrresponse.value = ResponseItemVO(
                        isError = true,
                        errorMessage = getMessageFromAllResponse(nameofFunction(this),t.message!!)
                    )
                }

                override fun onResponse(call: Call<String>, response: Response<String>) {

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

                        //Log.i("VERDNATURA:","UserError ${response.raw().message().toString()}")
                        // var message = response.raw().message().toString()

                        _qrresponse.value = ResponseItemVO(
                            response = "",
                            isError = true,
                            errorMessage =contextApp.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())
                            )


                    }
                }


            })
    }
}



