package com.atmob.flutter_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.channelreader.ChannelReader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import java.util.Map;

public class UmengHelper {

    private static String umengAppKey;

    private UmengHelper() {

    }

    public static void preInit(@NonNull Application application, String appKey) {
        UmengHelper.umengAppKey = appKey;
        UMConfigure.preInit(application, appKey, ChannelReader.getChannel(application));
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);

        ProcessLifecycleOwner.get().getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
            if (event == Lifecycle.Event.ON_DESTROY) {
                saveData(application);
            }
        });
    }


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


    public static void initCommon(@NonNull Context context, String appKey) {
        if (appKey == null) {
            appKey = umengAppKey;
        }
        initAfterGrantedAgreement(context, appKey);
    }

    public static void initAfterGrantedAgreement(@NonNull Context context, String appKey) {
        UMConfigure.init(context, appKey, ChannelReader.getChannel(context), UMConfigure.DEVICE_TYPE_PHONE, null);//last param is PushSecretKey
    }


    /**
     * 上报用户是否同意隐私政策
     *
     * @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);
    }
}
