package com.example.iot_controlhost.utils.log;


import android.content.Context;
import android.content.Intent;

import com.jakewharton.processphoenix.ProcessPhoenix;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

import java.util.Arrays;

public class CrashHandlerUtil implements Thread.UncaughtExceptionHandler {
    /**
     * 饿汉式单例模式
     */
    private static CrashHandlerUtil crashHandlerUtil = new CrashHandlerUtil();
    private Thread.UncaughtExceptionHandler mDefaultCaughtExceptionHandler;
    private Context mContext;

    private CrashHandlerUtil() {
        // 私有构造函数，确保单例模式
    }

    public static CrashHandlerUtil getInstance() {
        return crashHandlerUtil;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultCaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        ex.printStackTrace();
        MyLog.appError("软件已崩溃,重启应用：" + getFormattedException(ex));
        // 先启动重启保护，任何日志或数据库异常都不能阻断恢复流程。
        new Thread(() -> {
            try { Thread.sleep(500); } catch (Exception ignored) { }
            ProcessPhoenix.triggerRebirth(mContext);
        }).start();
        UserLog.systemErrorImmediately("程序运行异常，系统将自动重启");

    }

    public String getFormattedException(Throwable throwable) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("异常详情：\n")
                .append("异常类型：").append(throwable.getClass().getName()).append("\n")
                .append("异常消息：").append(throwable.getMessage() != null ? throwable.getMessage() : "无").append("\n");

        StackTraceElement[] stackTrace = throwable.getStackTrace();
        if (stackTrace != null && stackTrace.length > 0) {
            stringBuilder.append("异常位置：").append(stackTrace[0].toString()).append("\n");
        }

        stringBuilder.append("完整堆栈跟踪：\n");
        for (StackTraceElement element : stackTrace) {
            stringBuilder.append("\t").append(element.toString()).append("\n");
        }

        Throwable cause = throwable.getCause();
        if (cause != null) {
            stringBuilder.append("异常原因：").append(cause.toString()).append("\n");
        }

        return stringBuilder.toString();
    }


}
