package com.vpn.fastestvpnservice.viewmodels

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.vpn.fastestvpnservice.beans.DataResponse
import com.vpn.fastestvpnservice.beans.UserResponse
import com.vpn.fastestvpnservice.retrofit.RetrofitNetworkHandling
import com.vpn.fastestvpnservice.retrofit.WebServiceFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class SignUpViewModel: ViewModel() {

    var mutableLiveData = MutableLiveData<DataResponse<UserResponse>?>()
    var liveDataSignUp: LiveData<DataResponse<UserResponse>?> = mutableLiveData

    var mutableLiveDataStatus = MutableLiveData<Boolean>()
    var mutableLiveDataMessage = MutableLiveData<String>()

    private var mutableLiveDataSignUpStatus = MutableLiveData<Boolean>(false)
    var liveDataSignUpStatus: LiveData<Boolean> = mutableLiveDataSignUpStatus

    fun signUp(email: String, password: String) {
        WebServiceFactory.getInstance().signup(email, password, "no-name")
            .enqueue(RetrofitNetworkHandling<Any?>(object :
            RetrofitNetworkHandling.ResponseCallback<Any?>{
                override fun onSuccess(call: Call<Any?>?, response: Any?) {
                    Log.d("test_api_response", "signup::")
                    try {
                        val gson = Gson()
                        val jsonString = gson.toJson(response)
                        val type = object : TypeToken<DataResponse<UserResponse>>() {}.type
                        val data = gson.fromJson<DataResponse<UserResponse>>(jsonString, type)

                        Log.d("test_api_response", "signup:: ${data.status}")

                        data.let {
                            mutableLiveData.value = data
                        }
                    } catch (ex: Exception) {
                        Log.d("test_api_response", "signup:: catch")
                        mutableLiveDataSignUpStatus.value = false
                        mutableLiveData.value = null
                    }
                }

                override fun onFail(call: Call<Any?>?, response: Any?) {
                    Log.d("test_api_response", "signup:: onFail")
                    mutableLiveData.value = null
                    mutableLiveDataSignUpStatus.value = false
                }

                override fun onError(call: Call<Any?>?, response: Any?) {
                    Log.d("test_api_response", "signup:: onError")
                    mutableLiveData.value = null
                    mutableLiveDataSignUpStatus.value = false
                }

            }))
    }

    fun setSignUpStatus(status: Boolean) {
        mutableLiveDataSignUpStatus.value = status
    }
}