package com.ydl.ydlcommon.base

import android.app.Application
import android.content.Context
import android.support.multidex.MultiDex
import com.ydl.ydlcommon.base.config.GlobalConfig
import com.ydl.ydlcommon.base.config.IApp
import com.ydl.ydlcommon.base.delegate.AppDelegate
import com.ydl.ydlcommon.base.delegate.IAppLifecycles
import com.ydl.ydlcommon.utils.YDLPreconditions
import io.flutter.view.FlutterMain

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

    private var mAppDelegate: IAppLifecycles? = null

    companion object {

        lateinit var instance: BaseApp

        fun getApp(): Application {
            return instance
        }
    }

    /**
     * 这里会在 [BaseApp.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)


        //Flutter 初始化需要在主线程中执行
        FlutterMain.startInitialization(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()
    }
}
