package com.ydl.ydlcommon.app

import android.annotation.SuppressLint
import android.app.Application
import android.os.Build
import com.alibaba.android.arouter.launcher.ARouter
import com.bun.miitmdid.core.JLibrary
import com.ydl.devicesidlib.DeviceIDHelper
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.UpLoadLogUtils
import com.ydl.ydlcommon.utils.AppProgressUtils
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlnet.client.exception.ApiException
import com.yidianling.common.tools.RxTool
import io.reactivex.plugins.RxJavaPlugins


/**
 * 用于获取全局 context 和初始化一些第三方库
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/27
 */
@SuppressLint("StaticFieldLeak")
object YdlRepository {

    // 需要在主 module 的 application 的 onCreate 方法中调用此方法
    fun initApp(app: Application,isDebug:Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            JLibrary.InitEntry(app)
        }
        if (AppProgressUtils.isMainProcess(app)){
            DeviceIDHelper.getInstance().init(app.applicationContext)
        }
        LogHelper.getInstance().deleteExpireLogSync()
        LogUtil.debug = BaseApp.instance.getGlobalConfig().appDebug
        com.yidianling.common.tools.LogUtil.debug = BaseApp.instance.getGlobalConfig().appDebug
        //初始化工具类
        RxTool.init(app)
        BuryPointUtils.init()

//        if (LeakCanary.isInAnalyzerProcess(app)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return
//        }
//        refWatcher = LeakCanary.install(app)
        initARouter(app, isDebug)
        initRxPlugin()
    }

    private fun initRxPlugin() {
        //保障RxJava调用链流程不会崩溃
        RxJavaPlugins.setErrorHandler {
            LogUtil.e("RxJava ErrorHandler ---->: $it")
            try {
                val apiException = ApiException.handleException(it)
                UpLoadLogUtils.upLoadLog(
                    "RxJava Error Handler ", apiException.code, apiException.message?:""
                )
            } catch (e: Exception) {
                LogUtil.d("RxJava ErrorHandler UpLoad Log Error ---->: $it")
            }
        }
    }

    /**
     * 初始化阿里路由
     */
    private fun initARouter(app: Application,isDebug:Boolean) {
        if (isDebug) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(app)
    }
}