package com.datarecovery.master.sdk.umeng;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.atmob.user.AtmobUser;
import com.datarecovery.master.BuildConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.Map;

public class UmengHelper {

    private static final String UMENG_APP_KEY = BuildConfig.UMENG_APP_KEY;

    private UmengHelper() {

    }

    public static void init(@NonNull Application application) {
        if (BuildConfig.DEBUG) {
            return;
        }
        final String channel = AtmobUser.getAtmobChannel();
        UMConfigure.setLogEnabled(false);
        UMConfigure.preInit(application, UMENG_APP_KEY, channel);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        if (AtmobUser.isPolicyGranted()) {
            initAfterGrantedAgreement(application);
        }
        ProcessLifecycleOwner.get().getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
            if (event == Lifecycle.Event.ON_DESTROY) {
                saveData(application);
            }
        });
    }

    public static void initAfterGrantedAgreement(@NonNull Context context) {
        if (BuildConfig.DEBUG) {
            return;
        }
        final String channel = AtmobUser.getAtmobChannel();
        UMConfigure.init(context, UMENG_APP_KEY, channel, UMConfigure.DEVICE_TYPE_PHONE, null);//last param is PushSecretKey
    }

    /**
     * 当程序退出时，用于保存统计数据
     */
    public static void saveData(Context context) {
        MobclickAgent.onKillProcess(context.getApplicationContext());
    }

    /**
     * 上报用户是否同意隐私政策
     *
     * @param granted 是否同意
     */
    public static void submitPolicyGrantResult(Context context, boolean granted) {
        UMConfigure.submitPolicyGrantResult(context.getApplicationContext(), granted);
    }

    /**
     * 事件上报
     *
     * @param eventId 事件id
     */
    public static void reportEvent(Context context, String eventId) {
        MobclickAgent.onEvent(context, eventId);
    }

    /**
     * 携带信息的事件上报
     *
     * @param eventId 事件id
     * @param map     额外信息, object类型由第一次上报时的为准, 后续不能更改
     */
    public static void reportEvent(Context context, String eventId, Map<String, Object> map) {
        MobclickAgent.onEventObject(context, eventId, map);
    }
}