package com.ysnows.base.base

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.os.Process
import com.billy.cc.core.component.BuildConfig
import com.billy.cc.core.component.CC
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadSir
import com.tencent.mmkv.MMKV
import com.ysnows.base.config.IConfig
import com.ysnows.base.config.IConfigInit
import com.ysnows.base.emptyview.callback.*
import io.reactivex.plugins.RxJavaPlugins

abstract class BApp : Application(), IConfigInit {
    override fun onCreate() {
        super.onCreate()
        if (shouldInit()) {
            instance = this

            initUmeng()
            initMMKV()
            initRxJava()
            initCC()
            initLoadSir()
            init()
        }
    }

    protected abstract fun init()
    private fun initUmeng() {
        //            UMConfigure.init(this, "5bc6e22cb465f50d120001f9", "default", 0, null);
    }


    private fun initRxJava() {
        RxJavaPlugins.setErrorHandler {
            it.printStackTrace()
        }
    }

    private fun initCC() {
        CC.enableVerboseLog(com.ysnows.base.BuildConfig.DEBUG)
        CC.enableDebug(com.ysnows.base.BuildConfig.DEBUG)
//        CC.enableRemoteCC(BuildConfig.DEBUG);
    }

    private fun initMMKV() {
        val rootDir = MMKV.initialize(this)
    }

    private fun initLoadSir() {
        LoadSir.beginBuilder()
                .addCallback(ErrorCallback())
                .addCallback(EmptyCallback())
                .addCallback(LoadingCallback())
                .addCallback(TimeoutCallback())
                .addCallback(CustomCallback())
                .addCallback(ToLoginCallback())
                .addCallback(AnimateCallback())
                .setDefaultCallback(SuccessCallback::class.java)
                .commit()
    }

    private fun shouldInit(): Boolean {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val processInfos = am.runningAppProcesses
        val mainProcessName = packageName
        val myPid = Process.myPid()
        for (info in processInfos) {
            if (info.pid == myPid && mainProcessName == info.processName) {
                return true
            }
        }
        return false
    }

    companion object {
        const val TAG = "MiPush"
        private var instance: BApp? = null
        lateinit var config: IConfig

        @JvmStatic
        fun instance(): BApp? {
            return instance
        }
    }


}
