package cn.org.bjca.trust.push

import cn.org.bjca.trust.push.common.SendMessageHelper
import java.io.PrintWriter
import java.io.StringWriter
import java.io.Writer

/**
 * 日志收集
 */
object CrashHandler : Thread.UncaughtExceptionHandler {

    // 系统默认的 UncaughtException 处理类
    private var mDefaultHandler: Thread.UncaughtExceptionHandler? = null

    fun init() {
        // 获取系统默认的 UncaughtException 处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        // 设置该 CrashHandler 为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    override fun uncaughtException(t: Thread, e: Throwable) {
        handleException(e)
        // 让系统默认的异常处理器继续处理
        mDefaultHandler?.uncaughtException(t, e)
    }

    private fun handleException(ex: Throwable) {
        val writer: Writer = StringWriter()
        val printWriter = PrintWriter(writer)
        ex.printStackTrace(printWriter)
        var cause: Throwable? = ex.cause
        while (cause != null) {
            cause.printStackTrace(printWriter)
            cause = cause.cause
        }
        printWriter.close()
        SendMessageHelper.sendLogMessage(writer.toString())

    }

}