package cn.org.bjca.trust.push

import android.os.Build
import cn.org.bjca.trust.push.common.CommonHelper
import cn.org.bjca.trust.push.common.LogHelper

/**
 * 日志收集
 */
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(e: Throwable?) {
        e?.let {
            LogHelper.e(BuildConfig.versionCode.toString())
            LogHelper.e(BuildConfig.versionName)
            val fields = Build::class.java.declaredFields
            for (field in fields) {
                try {
                    field.isAccessible = true
//                    infos.put(field.name, field[null].toString())
                    LogHelper.e(field.name + " : " + CommonHelper.anyToString(field[null]))
                } catch (e: Exception) {
                    LogHelper.e("an error occured when collect crash info", e)
                }
            }
        }

    }

}