package com.vpn.fastestvpnservice.viewmodels

import android.content.Context
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.ProductFeatures
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
import com.vpn.fastestvpnservice.retrofit.RetrofitNetworkHandling
import com.vpn.fastestvpnservice.retrofit.WebServiceFactory
import retrofit2.Call

class SubscriptionViewModel constructor(context: Context): ViewModel() {

    var mutableLiveDataProducts = MutableLiveData<DataResponse<ArrayList<ProductFeatures>>>()
    var liveDataProducts: LiveData<DataResponse<ArrayList<ProductFeatures>>> = mutableLiveDataProducts

    var mutableLiveDataProductsErrorStatus = MutableLiveData<Boolean>()

    var preferenceHelper: BasePreferenceHelper

    init {
        preferenceHelper = BasePreferenceHelper(context)
    }
    fun getProducts(){
        WebServiceFactory.getInstance().getProducts().enqueue(
            RetrofitNetworkHandling<Any>(object :
                RetrofitNetworkHandling.ResponseCallback<Any>{
                override fun onSuccess(call: Call<Any>?, response: Any?) {

                    try {
                        val gson = Gson()
                        val jsonString = gson.toJson(response)
                        val type = object : TypeToken<DataResponse<ArrayList<ProductFeatures>>>() {}.type
                        val data = gson.fromJson<DataResponse<ArrayList<ProductFeatures>>>(jsonString, type)

                        Log.d("test_api_response p", "Products try = ${data.status} ${data.message}")

                        data?.data?.let {
                            preferenceHelper.saveFeaturesData(it)
                        }
                        mutableLiveDataProducts.value = data
                        mutableLiveDataProductsErrorStatus.value = false

                    } catch (ex: Exception) {
                        Log.d("test_api_response", "Products catch:")
                        mutableLiveDataProductsErrorStatus.value = true
                    }
                }

                override fun onFail(call: Call<Any>?, response: Any?) {
                    Log.d("test_api_response", "Products onFail: ")
                    mutableLiveDataProductsErrorStatus.value = true
                }

                override fun onError(call: Call<Any>?, response: Any?) {
                    Log.d("test_api_response", "Products onError: ")
                    mutableLiveDataProductsErrorStatus.value = true
                }
            }
            )
        )
    }

}