package com.colorful.keyboard.theme.firebase

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import com.colorful.keyboard.theme.App
import com.colorful.keyboard.theme.BuildConfig
import com.colorful.keyboard.theme.myutil.AppSharedPreferences
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.FirebaseRemoteConfigSettings
import com.google.firebase.remoteconfig.FirebaseRemoteConfigValue
import java.lang.ref.WeakReference

class RemoteConfig {

    private var ctx: Context? = null
    private var mFirebaseRemoteConfig: FirebaseRemoteConfig? = null

    //配置是否初始化成功
    private var isInit = false

    //上次获取数据的时间
    private var lastFetchTime: Long = 0
    private val handler = MHandler(this)

    companion object {
        const val MSG_REFRESH_CONFIG = 1
        val instance: RemoteConfig by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RemoteConfig()
        }
    }

    fun init(ctx: Application) {
        this.ctx = ctx
        initConfig()
        fetchConfig()
        onConfigUpdate()
    }

    private fun initConfig() {
        var intervalTime = (60 * 10).toLong()
        //如果是开发状态，则将提取时间缩短
        if (BuildConfig.DEBUG) {
            intervalTime = (60 * 5).toLong()
        }
        mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
        val configSettings =
            FirebaseRemoteConfigSettings.Builder() //默认值12小时的最短提取间隔，如果在间隔内取值，则优先取上次的结果
                .setMinimumFetchIntervalInSeconds(intervalTime).build()
        mFirebaseRemoteConfig!!.setConfigSettingsAsync(configSettings)
    }

    private fun onConfigUpdate() {
        mFirebaseRemoteConfig!!.addOnConfigUpdateListener(object : ConfigUpdateListener {
            override fun onUpdate(configUpdate: ConfigUpdate) {
                try {
//                    if (configUpdate.updatedKeys.contains(Constants.KEY_SHOULD_ENTER_MUSIC_JSON)) {
//
//                    }
                    mFirebaseRemoteConfig!!.activate().addOnCompleteListener { task ->
                        if (task.isSuccessful) {
                            updateData("onConfigUpdate", mFirebaseRemoteConfig!!.all)
                        }
                    }
                } catch (ignore: Exception) {
                }
            }

            override fun onError(error: FirebaseRemoteConfigException) {
            }
        })
    }

    @SuppressLint("LongLogTag")
    private fun fetchConfig() {
        //这里可能会抛出异常 FirebaseRemoteConfigFetchThrottledException
        try {
            mFirebaseRemoteConfig!!.fetchAndActivate().addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    isInit = true
                    lastFetchTime = System.currentTimeMillis()
                    updateData("fetchAndActivate", mFirebaseRemoteConfig!!.all)
                    //24小时后，重新再去获取
                    handler.removeMessages(MSG_REFRESH_CONFIG)
                    handler.sendEmptyMessageDelayed(
                        MSG_REFRESH_CONFIG, (1000 * 60 * 60 * 24).toLong()
                    )
                } else {
                    //这里需要重新再去获取
                    handler.removeMessages(MSG_REFRESH_CONFIG)
                    handler.sendEmptyMessageDelayed(MSG_REFRESH_CONFIG, (1000 * 60 * 15).toLong())
                }
            }
        } catch (ignore: Exception) {
        }
    }

    private fun updateData(from: String, all: Map<String, FirebaseRemoteConfigValue>) {
        val appSharedPreferences =  AppSharedPreferences(App.app)
        for ((key, value) in all) {
            try {
                Log.d("colorful-config","from->$from key->$key value->${value.asString()}")
                if (TextUtils.equals(Constants.KEY_SHOW_AD_INTERVAL_TIME, key)) {
                    val t = value.asString()
                    appSharedPreferences.setShowAdIntervalTime(t.toLong())
                }
            } catch (ignore: Exception) {

            }
        }
    }

    private class MHandler(remoteConfig: RemoteConfig) : Handler() {
        private val weakReference: WeakReference<RemoteConfig> = WeakReference(remoteConfig)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val remoteConfig = weakReference.get()
            if (remoteConfig?.ctx != null) {
                if (msg.what == MSG_REFRESH_CONFIG) {
                    remoteConfig.fetchConfig()
                }
            }
        }
    }

}