package com.abbidot.tracker.util

import android.content.Context
import android.os.Process
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil

/**
 *Created  by .yzq on 2025/11/14/周五.
 * @link
 * @description:
 */
class CrashHandler : Thread.UncaughtExceptionHandler {

    private val mTAG = "CrashHandler"
    private lateinit var mContext: Context
//    private var mDefaultHandler: Thread.UncaughtExceptionHandler? = null

    override fun uncaughtException(t: Thread, e: Throwable) {
        LogUtil.e(mTAG, "当前进程id:" + Process.myPid())
//        LogUtil.e(mTAG, "异常信息:" + Log.getStackTraceString(e))

//        mDefaultHandler?.uncaughtException(t, e)

        MMKVUtil.putBoolean(MMKVKey.isCrash, true)

//        restartApp()
    }


    fun init(context: Context) {
        mContext = context.applicationContext
//        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler()!!
        Thread.setDefaultUncaughtExceptionHandler(this)
    }


    private fun restartApp() {
//        val intent = mContext.packageManager.getLaunchIntentForPackage(mContext.packageName)
//        if (intent != null) {
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
//            mContext.startActivity(intent)
//            Process.killProcess(Process.myPid())
//            exitProcess(0)
//        }


//        val intent = mContext.packageManager.getLaunchIntentForPackage(mContext.packageName)
//        intent?.apply {
//            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
//            mContext.startActivity(this)
//            Process.killProcess(Process.myPid())
//            System.exit(0)
//        }

//        Process.killProcess(Process.myPid())
//
//        val intent = Intent(mContext, SplashActivity::class.java)
//        val restartIntent = PendingIntent.getActivity(
//            mContext.applicationContext,
//            0,
//            intent,
//            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT
//        );
//        //退出程序
//        val mgr =
//            mContext.applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//        // 1秒钟后重启应用
//        mgr.set(
//            AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent
//        )
//        exitProcess(0)
    }
}