package com.wall.photography.wallpaper.firebase

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
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 com.wall.photography.wallpaper.MyApp

import java.lang.ref.WeakReference
import com.wall.photography.wallpaper.BuildConfig
import com.wall.photography.wallpaper.util.Sp

class RemoteConfigNew {


    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: RemoteConfigNew by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RemoteConfigNew()
        }
    }

    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) {
                Log.d(MyApp.TAG, "Updated keys: " + configUpdate.updatedKeys)
                try {
                    mFirebaseRemoteConfig!!.activate().addOnCompleteListener { task ->
                        if (task.isSuccessful) {
                            updateData("onConfigUpdate", mFirebaseRemoteConfig!!.all)
                        }
                    }
                } catch (ignore: Exception) {
                }
            }

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

    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 {
                    //15分钟后重新再去获取
                    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>) {
        for ((key, value) in all) {
            try {
                Log.d(
                    MyApp.TAG, "from = " + from + "Key = " + key + " Value = " + value.asString()
                )
                if (TextUtils.equals(RemoteConfigKey.KEY_AD_SHOW_INTERVAL, key)) {
                    Sp.getInstance(MyApp.application)
                        .putLong(RemoteConfigKey.KEY_AD_SHOW_INTERVAL, value.asLong()).commit()
                }

            } catch (ignore: Exception) {

            }
        }
    }

    private class MHandler(remoteConfig: RemoteConfigNew) : Handler(Looper.getMainLooper()) {
        private val weakReference: WeakReference<RemoteConfigNew>

        init {
            weakReference = 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()
                }
            }
        }
    }

}