package com.vpn.fastestvpnservice.viewmodels

import android.content.Context
import android.util.Log
import androidx.compose.ui.platform.LocalContext
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.IpInfo
import com.vpn.fastestvpnservice.beans.TokenResponse
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
import com.vpn.fastestvpnservice.retrofit.RetrofitNetworkHandling
import com.vpn.fastestvpnservice.retrofit.WebServiceFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call

class HomeViewModel constructor(context: Context, scope: CoroutineScope): ViewModel() {
    var prefHelper: BasePreferenceHelper = BasePreferenceHelper(context)
    var scope: CoroutineScope

    val mutableLiveDataIpInfo = MutableLiveData<IpInfo?>()

    var _mutableLiveDataValidate = MutableLiveData<DataResponse<TokenResponse>>()
    var liveDataValidate : LiveData<DataResponse<TokenResponse>> = _mutableLiveDataValidate
    var mutableLiveDataValidateError = MutableLiveData<String>()

    var _isConnect = MutableLiveData<Boolean>(prefHelper.getConnectState())
    var isConnect: LiveData<Boolean> = _isConnect

    init {
        prefHelper = BasePreferenceHelper(context)
        this.scope = scope
    }

    fun setConnectState(state: Boolean) {
        Log.d("isConnect_State", "setConnectState1:: $state")

        _isConnect.postValue(state)

//        scope.launch(Dispatchers.Main) {
//            _isConnect.value = state
//        }

        Log.d("isConnect_State", "setConnectState2:: $state")
        prefHelper.setConnectState(state)
        Log.d("isConnect_State", "setConnectState3:: $state")
    }

    fun getIp() {
        WebServiceFactory.getInstance().getIp()
            .enqueue(RetrofitNetworkHandling<Any>(object :
                RetrofitNetworkHandling.ResponseCallback<Any> {
                override fun onSuccess(call: Call<Any>?, response: Any?) {
                    Log.d("test_api_response", "ip = onSuccess")
                    try {
                        val gson = Gson()
                        val jsonString = gson.toJson(response)
                        val type = object : TypeToken<IpInfo>() {}.type
                        val data = gson.fromJson<IpInfo>(jsonString, type)
                        mutableLiveDataIpInfo.value = data
                        if (data != null) {
                            prefHelper?.saveIpInfo(data)
                        }
                    Log.d("test_api_response", "ip = " + data?.country.toString() + " " + data?.countryCode)
                    } catch (ex: Exception) { }
                }

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

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

    fun validatePassword(
        email: String,
        password: String,
        platform: String,
        version: String
    ) {

        WebServiceFactory.getInstance().validatePassword(email, password, platform, version)?.enqueue(
            RetrofitNetworkHandling<Any>(object :
                RetrofitNetworkHandling.ResponseCallback<Any> {
                override fun onSuccess(call: Call<Any>?, response: Any?) {
                    try {
                        Log.d("test_api_response", "validatePassword onSuccess: try")
                        val gson = Gson()
                        val jsonString = gson.toJson(response)
                        val type = object : TypeToken<DataResponse<TokenResponse?>?>() {}.type
                        val data = gson.fromJson<DataResponse<TokenResponse>>(jsonString, type)
                        _mutableLiveDataValidate.value = data
                        Log.d("test_api_validate", "data = ${data.message}")

                    } catch (ex: Exception) {
                        Log.d("test_api_response", "validatePassword onSuccess: catch")
                    }

                }

                override fun onFail(call: Call<Any>?, response: Any?) {
                    Log.d("test_api_response", "validatePassword onFail")
                    mutableLiveDataValidateError.value = "Something went wrong. Please try again"
                }

                override fun onError(call: Call<Any>?, response: Any?) {
                    Log.d("test_api_response", "validatePassword onError")
                    mutableLiveDataValidateError.value = "Something went wrong. Please try again"
                }
            })
        )
    }
}