package xn.xxp.app;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.AsyncTask;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.github.anrwatchdog.ANRWatchDog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hikvision.hatomplayer.HatomPlayerSDK;
import com.kongzue.dialogx.DialogX;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;

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

import coil.Coil;
import coil.ComponentRegistry;
import coil.ImageLoader;
import coil.decode.SvgDecoder;
import core.util.ScreenAdapter;
import http.vo.response.LaboratoryVo;
import http.vo.response.UserVo;
import play.AppConfig;
import xn.xxp.utils.StringNullAdapter;
import xn.xxp.utils.Tool;

@SuppressLint("SdCardPath")
public class LabApp extends Application {

    public static Gson gson;

    /**
     * 实验室信息
     */
    public static LaboratoryVo laboratory;

    /**
     * 当前登录人
     */
    public static UserVo userVo;

    @Override
    public void onCreate() {
        super.onCreate();
        HatomPlayerSDK.init(this, "", true);
        Tool.INSTANCE.openAdb();
        gson = GsonUtils.getGson().newBuilder().serializeNulls().registerTypeAdapter(String.class, new StringNullAdapter()).create();
        GsonUtils.setGsonDelegate(gson);
        GsonUtils.setGson("defaultGson", gson);
        Tool.INSTANCE.getPermission();
        DialogX.init(this);
        initAnrDog();
        Glide.get(this).clearMemory();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                Glide.get(LabApp.this).clearDiskCache();
            }
        });
        ScreenAdapter.INSTANCE.initAppDensity(this);
        initLog();
        initCrash();
        initX5();
        initCoil();
        AppConfig.INSTANCE.initHikvision(this);
    }

    private void initCoil() {
        ComponentRegistry.Builder builder = new ComponentRegistry.Builder();
        builder.add(new SvgDecoder.Factory());
        ImageLoader imageLoader = new ImageLoader.Builder(this).components(builder.build()).build();
        Coil.setImageLoader(imageLoader);
    }

    private void initX5() {
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        stringObjectMap.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(stringObjectMap);
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                LogUtils.d("x5", "onCoreInitFinished");
            }

            @Override
            public void onViewInitFinished(boolean b) {
                LogUtils.d("x5", "初始化结果" + b);
            }
        });
    }

    private void initCrash() {
        final String crashPath = "/sdcard/logs/crash/";
        FileUtils.createOrExistsDir(crashPath);
        CrashUtils.init(crashPath, crashInfo -> {
            LogUtils.e("捕获Crash重启", crashInfo);
            Tool.INSTANCE.reStartApp("捕获Crash重启");
        });
    }

    // 日志记录
    private void initLog() {
        final String logPath = "/sdcard/logs/";
        FileUtils.createOrExistsDir(logPath);
        LogUtils.Config config = LogUtils.getConfig();
        config.setLogSwitch(true);
        config.setConsoleSwitch(true);
        config.setLog2FileSwitch(true);
        config.setDir(logPath);
        config.setFilePrefix(AppUtils.getAppName());
        config.setBorderSwitch(true);
        config.setSaveDays(30);

    }

    // 看门狗
    public void initAnrDog() {
        new ANRWatchDog().setIgnoreDebugger(false).setANRListener(anrError -> {
            LogUtils.e(anrError, anrError.getMessage());
            ThreadUtils.runOnUiThread(() -> {
                Toast.makeText(ActivityUtils.getTopActivity(), "检测到应用卡顿,即将重启应用恢复!", Toast.LENGTH_LONG).show();
                ThreadUtils.runOnUiThreadDelayed(() -> {
                    int anrSize = SPUtils.getInstance().getInt("ANR_size", 0);
                    if (anrSize > 5) {
                        SPUtils.getInstance().put("ANR_size", 0);
                        Tool.INSTANCE.reboot();
                    } else {
                        SPUtils.getInstance().put("ANR_size", ++anrSize);
                        Tool.INSTANCE.reStartApp("ANR 重启应用");
                    }
                }, 3000);
            });
        }).setReportAllThreads().start();
    }
}
