package com.yidianling.ydlcommon.core.base

import android.app.Application
import android.content.Context
import android.support.multidex.MultiDex
import com.yidianling.ydlcommon.core.base.delegate.AppDelegate
import com.yidianling.ydlcommon.core.base.delegate.IAppLifecycles
import com.yidianling.ydlcommon.core.utils.YDLPreconditions
import com.yidianling.ydlcommon.core.base.config.GlobalConfig
import com.yidianling.ydlcommon.core.base.config.IApp

/**
 * Created by haorui on 2019-08-21 .
 * Des: 基础Application
 */
class BaseApplication : Application(), IApp {

    private var mAppDelegate: IAppLifecycles? = null

    companion object {

        lateinit var instance: BaseApplication

        fun getApp(): Application {
            return instance
        }
    }

    /**
     * 这里会在 [BaseApplication.onCreate] 之前被调用,可以做一些较早的初始化
     * 常用于 MultiDex 以及插件化框架的初始化
     *
     * @param base
     */
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        instance = this;
        MultiDex.install(this)
        if (mAppDelegate == null)
            this.mAppDelegate = AppDelegate(base)
        this.mAppDelegate!!.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        if (mAppDelegate != null)
            this.mAppDelegate!!.onCreate(this)
    }

    /**
     * 在模拟环境中程序终止时会被调用
     */
    override fun onTerminate() {
        super.onTerminate()
        if (mAppDelegate != null)
            this.mAppDelegate!!.onTerminate(this)
    }

    override fun getGlobalConfig(): GlobalConfig {
        YDLPreconditions.checkNotNull(mAppDelegate, "%s cannot be null", AppDelegate::class.java.name)
        YDLPreconditions.checkState(
            mAppDelegate is IApp,
            "%s must be implements %s",
            mAppDelegate!!::class.java.name,
            IApp::class.java.name
        )

        return (mAppDelegate as IApp).getGlobalConfig()
    }
}
