package com.assimilate.alltrans.common

import android.content.Context
import android.util.Log
import com.assimilate.alltrans.MyApp
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ConfigUpdate
import com.google.firebase.remoteconfig.ConfigUpdateListener
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigException
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings

class RemoteConfigManager(private val context: Context) {

    private val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig

    init {
        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = 3600
        }
        remoteConfig.setConfigSettingsAsync(configSettings)

        remoteConfig.fetchAndActivate()
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val updated = task.result
                    Log.d(TAG, "Config params updated: $updated")
                   // Toast.makeText(context, "Fetch and activate succeeded", Toast.LENGTH_SHORT).show()
                    saveConfigValuesToAppStore()
                } else {
                   // Toast.makeText(context, "Fetch failed", Toast.LENGTH_SHORT).show()
                }
            }

        remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener {
            override fun onUpdate(configUpdate: ConfigUpdate) {
                Log.d(TAG, "Updated keys: " + configUpdate.updatedKeys)
                if (configUpdate.updatedKeys.contains(MyApp.Config.adKey)) {
                    remoteConfig.activate().addOnCompleteListener {
                        saveConfigValuesToAppStore()
                    }
                }
            }

            override fun onError(error: FirebaseRemoteConfigException) {
                Log.w(TAG, "Config update error with code: " + error.code, error)
            }
        })
    }

    private fun saveConfigValuesToAppStore() {
        val appStore = AppStore(context)
        val adValue = remoteConfig.getString(MyApp.Config.adKey)
        appStore.saveString(MyApp.Config.adKey, adValue)
    }

    companion object {
        private const val TAG = "RemoteConfigManager"
    }
}
