package com.datarecovery.master.sdk.bugly;

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

import androidx.annotation.NonNull;

import com.atmob.common.runtime.ContextUtil;
import com.atmob.user.AtmobUser;
import com.datarecovery.master.BuildConfig;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.LinkedHashMap;
import java.util.Map;

public class BuglyHelper {

    private static final String BUGLY_APP_ID = BuildConfig.BUGLY_APP_ID;

    private BuglyHelper() {

    }

    /**
     * 初始化, 只在主进程中进行
     */
    public static void init(@NonNull Application application) {
        final Context applicationContext = application.getApplicationContext();
        CrashReport.initCrashReport(
                applicationContext,
                BUGLY_APP_ID,
                BuildConfig.DEBUG,
                getBuglyStrategy(applicationContext)
        );
        CrashReport.setIsDevelopmentDevice(applicationContext, BuildConfig.DEBUG);//设置开发设备
        if (AtmobUser.isPolicyGranted()) {
            initAfterGrantedAgreement();
        }
    }

    private static CrashReport.UserStrategy getBuglyStrategy(Context applicationContext) {
        final CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(applicationContext);
        strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
            @Override
            public synchronized Map<String, String> onCrashHandleStart(int i, String s, String s1, String s2) {
                LinkedHashMap<String, String> map = new LinkedHashMap<>();
//                String x5CrashInfo = WebView.getCrashExtraMessage(applicationContext);
//                map.put("x5crashInfo", x5CrashInfo);
                return map;
            }

        });
        return strategy;
    }

    public static void initAfterGrantedAgreement() {
        CrashReport.setDeviceModel(ContextUtil.getContext(), Build.MODEL);
    }


    public static void postCatchedException(Throwable throwable) {
        CrashReport.postCatchedException(throwable, Thread.currentThread());
    }

}