package com.hmg.hmgDr.globalErrorHandler

import android.content.Context
import android.content.Intent
import com.hmg.hmgDr.MainActivity
import com.hmg.hmgDr.globalErrorHandler.FileUtil.pushLog


class LoggingExceptionHandler(private val context: Context, ErrorFile: String) :
    Thread.UncaughtExceptionHandler {
    private val rootHandler: Thread.UncaughtExceptionHandler
    override fun uncaughtException(t: Thread, e: Throwable) {
        object : Thread() {
            override fun run() {
                pushLog("UnCaught Exception is thrown in $error$e")
                try {
                    sleep(500)
                    val intent = Intent(context, MainActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                    context.startActivity(intent)
                } catch (e1: Exception) {
                    e1.printStackTrace()
                }
            }
        }.start()
        rootHandler.uncaughtException(t, e)
    }

    companion object {
        private val TAG = LoggingExceptionHandler::class.java.simpleName
        lateinit var error: String
    }

    init {
        error = "$ErrorFile.error "
        rootHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this)
    }
}