package com.adealink.weparty.crash

import android.app.Application
import com.adealink.frame.base.AppBase
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.crash.report.CrashConfig
import com.adealink.frame.crash.report.CrashReporter
import com.adealink.frame.data.json.toJsonErrorNull
import com.adealink.frame.log.Log
import com.adealink.frame.log.Log.splitLog
import com.adealink.frame.log.data.APMLogType
import com.adealink.frame.log.data.ReportLogReason
import com.adealink.weparty.App
import com.adealink.weparty.apm.stat.APMStatEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

const val TAG_CRASH = "tag_crash"

fun initCrash(application: Application) {
    val config = CrashReporter.newBuilder(application)
        .setAppStartTime(App.instance.appStartTime)
        .setCrashEnabled(true)
        .setCrashCallback(object : CrashConfig.CrashCallback {

            override fun onCrash(map: MutableMap<String, String>) {
                map["is_emulator"] = App.instance.securityService.isLocalEmulator().toString()
//                map["web_url"] = WebModule.getLoadUrl()
//                map["weak_device"] = "${PerformanceHelper.isWeakDevice()}"
            }

            override fun reportCrash(map: MutableMap<String, String>) {
                if(!AppBase.isRelease) {
//                    CoroutineScope(Dispatcher.WENEXT_THREAD_POOL).launch {
//                        App.instance.logService.uploadLongString("crash${System.currentTimeMillis()})", "${toJsonErrorNull(map)}")
//                    }
                }
                APMStatEvent(APMStatEvent.Action.CRASH)
                    .apply {
                        addEventMap(map)
                    }
                    .send()
            }

            override fun uploadLog(crashJson: String) {
                CoroutineScope(Dispatcher.WENEXT_THREAD_POOL).launch {
                    val time = System.currentTimeMillis()
                    splitLog(crashJson)
                        .forEach { Log.i(TAG_CRASH, "crash($time) = $it") }
//                    App.instance.logService.uploadLongString("crash($time)", crashJson)
                    App.instance.logService.uploadLog(ReportLogReason.APM(APMLogType.CRASH))                }
            }

        })
        .build()
    Log.i(TAG_CRASH, "initCrash")
    CrashReporter.init(config)
}
