package com.guadou.lib_baselib.base

import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.guadou.basiclib.BuildConfig
import com.guadou.lib_baselib.core.BaseLibCore
import com.guadou.lib_baselib.utils.NetWorkUtil
import com.guadou.lib_baselib.view.WebViewManager

/**
 * 基类的Application
 */
open class BaseApplication : Application() {

    //全局的静态Gson对象
    companion object {
        lateinit var instance : BaseApplication
        val mGson = Gson()
        lateinit var networkType: NetWorkUtil.NetworkType   //此变量会在网络监听中被动态赋值

        //检查当前是否有网络
        fun checkHasNet(): Boolean {
            return networkType != NetWorkUtil.NetworkType.NETWORK_NO && networkType != NetWorkUtil.NetworkType.NETWORK_UNKNOWN
        }

        //当前用户是否登录
        var isUserLogin = false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        //获取到全局的网络状态
        networkType = NetWorkUtil.getNetworkType(this@BaseApplication.applicationContext)

        //全局的 CommUtil的初始化
        BaseLibCore.init(this, Handler(Looper.getMainLooper()), android.os.Process.myTid())

        //网络监听
        BaseLibCore.registerNetworkObserver(this)

        //ARouter初始化
        initRouter(this)

        //初始化WebView缓存容器
        WebViewManager.prepare(this)
    }

    private fun initRouter(application: Application) {
        if (BuildConfig.DEBUG) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(application)
    }

    //Dex分包
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onTerminate() {
        super.onTerminate()
        BaseLibCore.unregisterNetworkObserver(this)

        //销毁WebView缓存容器
        WebViewManager.destroy()
    }


    /**
     * 设置用户是否登录
     */
    protected fun setUserIsLogin(isLogin: Boolean) {
        isUserLogin = isLogin
    }

}