package tech.starwin.utils;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;


/**
 * Created by SiKang on 2018/10/11.
 * FireBase 功能辅助类
 */
public class FireBaseHelper {
    public static final String REST_URL = "rest_url";

    /**
     * click埋点，CONTENT_TYPE = view.getTag()
     */
    public static void LogClickEventByTag(View view) {
        if (view.getTag() != null && view.getTag() instanceof String) {
            logClickEventByName(view.getContext(), (String) view.getTag());
        }
    }

    /**
     * click埋点 CONTENT_TYPE = view.getText()
     */
    public static void LogClickEventByText(View view) {
        String itemName = "";
        if (view instanceof TextView) {
            itemName = ((TextView) view).getText().toString();
        } else if (view instanceof Button) {
            itemName = ((Button) view).getText().toString();
        }
        if (!TextUtils.isEmpty(itemName)) {
            logClickEventByName(view.getContext(), itemName);
        }
    }

    /**
     * click埋点
     */
    public static void logClickEventByName(Context context, String itemName) {
        Bundle bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "click_" + itemName);
        FirebaseAnalytics.getInstance(context).logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
    }


    /**
     * 获取FireBase RemoteConfig 并激活
     */
    private static final int CACHE_EXPIRATION_SECONDS = 60 * 5;//remoteConfig 刷新频率

    public static void fetchRemoteConfig() {
        final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
        config.fetch(CACHE_EXPIRATION_SECONDS)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            config.activateFetched();
                        }
                    }
                });
    }

}
