package com.reactlibrary.uMeng;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nonnull;

import androidx.annotation.NonNull;

public class UmAnalytics extends ReactContextBaseJavaModule {


    private static ReactApplicationContext reactContext;
    public static UmAnalytics instance;

    @NonNull
    @Override
    public String getName() {
        return "UmAnalytics";
    }

    public UmAnalytics(@Nonnull ReactApplicationContext context) {
        super(context);
        reactContext = context;
        instance = this;
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL);
    }

    /// 用于用户进行账户统计
    /// @param puid 用户ID
    @ReactMethod
    public void profileSignInWithPUID(String puid) {
        MobclickAgent.onProfileSignIn(puid);
    }


    /// Signoff调用后，不再发送账号内容。
    @ReactMethod
    public void profileSignOff() {
        MobclickAgent.onProfileSignOff();
    }

    /// 页面打开
    /// @param pageName 页面名称
    @ReactMethod
    public void beginLogPageView(String pageName) {
        MobclickAgent.onPageStart(pageName);
    }


    /// 页面结束
    /// @param pageName 页面名称
    @ReactMethod
    public void endLogPageView(String pageName) {
        MobclickAgent.onPageEnd(pageName);
    }


    /// 计数事件
    /// @param eventId 网站上注册的事件Id
    /// @param attributes 自定义属性
    @ReactMethod
    public void numEvent(String eventId, ReadableMap attributes) {

        Map<String,String> attrMap = new HashMap<String, String>();
        for (Map.Entry<String,Object> entry:attributes.toHashMap().entrySet()){
            if(entry.getValue() instanceof String){
                attrMap.put(entry.getKey(),(String) entry.getValue());
            }
        }
        MobclickAgent.onEvent(reactContext,eventId,attrMap);
    }

    /// 计算事件
    /// @param eventId 网站上注册的事件Id
    /// @param attributes 自定义属性
    /// @param number   数字
    @ReactMethod
    public void countEvent(String eventId, ReadableMap attributes, Integer number) {
        Map<String,String> attrMap = new HashMap<String, String>();
        for (Map.Entry<String,Object> entry:attributes.toHashMap().entrySet()){
            if(entry.getValue() instanceof String){
                attrMap.put(entry.getKey(),(String) entry.getValue());
            }
        }
        MobclickAgent.onEventValue(reactContext,eventId,attrMap,number);
    }

    /// 收集app适用过程中产生的Crash信息,统计SDK默认是开启Crash收集机制的
    /// 开启CrashReport收集, 默认YES(开启状态).
    /// @param value 设置为NO,可关闭友盟CrashReport收集功能.
    @ReactMethod
    public void setCrashReportEnabled(boolean value) {
        MobclickAgent.setCatchUncaughtExceptions(value);
    }

}
