package com.offline.music.playermp3.firebase;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.BuildConfig;
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.offline.music.playermp3.helper.CommonUtils;

import java.lang.ref.WeakReference;
import java.util.Map;

public class RemoteConfigJava {

    private static RemoteConfigJava remoteConfigJava;
    public static String key_open_type = "TYPE";

    //进入A面
    public static String value_open_type_0 = "0";
    //进入B面
    public static String value_open_type_1 = "1";


    private static int MSG_REFRESH_CONFIG = 1;


    private Context ctx;
    private FirebaseRemoteConfig mFirebaseRemoteConfig;

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

    //上次获取数据的时间
    private long lastFetchTime = 0;
    private MHandler handler = new MHandler(this);


    private Context getCtx() {
        return ctx;
    }

    public static RemoteConfigJava getInstance(){
        if(remoteConfigJava == null){
            remoteConfigJava = new RemoteConfigJava();
        }
        return remoteConfigJava;
    }
    private static class MHandler extends Handler {
        private WeakReference<RemoteConfigJava> weakReference;


        public MHandler(RemoteConfigJava remoteConfig) {
            super(Looper.getMainLooper());
            weakReference = new WeakReference<>(remoteConfig);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            RemoteConfigJava remoteConfig1 = weakReference.get();
            if (remoteConfig1.getCtx() != null) {
                if (msg.what == MSG_REFRESH_CONFIG) {
                    remoteConfig1.fetchConfig();
                }
            }
        }
    }

    public void init(Context context) {
        this.ctx = context;
        initConfig();
        fetchConfig();
        onConfigUpdate();
    }

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

    private void onConfigUpdate() {
        mFirebaseRemoteConfig.addOnConfigUpdateListener(new ConfigUpdateListener() {
            @Override
            public void onUpdate(@NonNull ConfigUpdate configUpdate) {
                CommonUtils.LogMsg("---FirebaseRemote---Updated keys: " + configUpdate.getUpdatedKeys());
                try {
                    mFirebaseRemoteConfig.activate().addOnCompleteListener(new OnCompleteListener<Boolean>() {
                        @Override
                        public void onComplete(@NonNull Task<Boolean> task) {
                            if (task.isSuccessful()) {
                                updateData("onConfigUpdate", mFirebaseRemoteConfig.getAll());
                            }
                        }
                    });
                } catch (Exception ignore) {
                    CommonUtils.LogMsg("---FirebaseRemote---onConfigUpdate Exception " + ignore.getMessage());
                }
            }

            @Override
            public void onError(@NonNull FirebaseRemoteConfigException error) {
                CommonUtils.LogMsg("---FirebaseRemote---onConfigUpdate onError " + error.getMessage());
            }
        });
    }

    private void fetchConfig() {
        //这里可能会抛出异常 FirebaseRemoteConfigFetchThrottledException
        try {
            mFirebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(new OnCompleteListener<Boolean>() {
                @Override
                public void onComplete(@NonNull Task<Boolean> task) {
                    if (task.isSuccessful()) {
                        isInit = true;
                        lastFetchTime = System.currentTimeMillis();
                        updateData("fetchAndActivate", mFirebaseRemoteConfig.getAll());
                        //24小时后，重新再去获取
                        handler.removeMessages(MSG_REFRESH_CONFIG);
                        handler.sendEmptyMessageDelayed(
                                MSG_REFRESH_CONFIG, 1000 * 60 * 60 * 24L);
                    } else {
                        //15分钟后重新再去获取
                        handler.removeMessages(MSG_REFRESH_CONFIG);
                        handler.sendEmptyMessageDelayed(MSG_REFRESH_CONFIG, 1000 * 60 * 15L);
                    }

                }
            });
        } catch (Exception exception) {
            CommonUtils.LogMsg("---FirebaseRemote--- exception = " + exception.getMessage());
        }
    }


    private void updateData(String from, Map<String, FirebaseRemoteConfigValue> all) {
        for (Map.Entry<String, FirebaseRemoteConfigValue> entry : all.entrySet()) {
            FirebaseRemoteConfigValue value = entry.getValue();
            String key = entry.getKey();
            CommonUtils.LogMsg("---FirebaseRemote---from = " + from + "Key = " + key + " Value = " + value.asString());

            if (TextUtils.equals(key_open_type, key)) {
                Sp.getInstance()
                        .putStringValue(key_open_type, value.asString()).commit();
            }
        }
    }
}
