package com.ydl.ydlcommon.base.delegate

import android.app.Application
import android.content.Context
import com.ydl.ydlcommon.app.YdlRepository
import com.ydl.ydlcommon.base.config.GlobalConfig
import com.ydl.ydlcommon.base.config.IApp
import com.ydl.ydlcommon.base.config.IConfigModule
import com.ydl.ydlcommon.utils.ManifestParser
import java.util.*


/**
 * Created by haorui on 2019-08-21 .
 * Des: BaseApp 代理类
 */
class AppDelegate(context: Context) : IAppLifecycles,IApp{


    private var mApplication: Application? = null
    private var mModules: List<IConfigModule>? = null

    private var mAppLifecycles: ArrayList<IAppLifecycles>? = ArrayList()
    private val mActivityLifecycleForRxLifecycle = ActivityDelegate()
    private var mGlobalConfig:GlobalConfig  ?=null

    init {

        //用反射, 将 AndroidManifest.xml 中带有 IConfigModule 标签的 class 转成对象集合（List<IConfigModule>）
        this.mModules = ManifestParser(context).parse()

        for (module in mModules!!) {
            //注入各 Module Application 的生命周期回调
            module.injectAppLifecycle(context, mAppLifecycles!!)
        }
    }

    override fun attachBaseContext(base: Context) {
        for (lifecycle in mAppLifecycles!!) {
            lifecycle.attachBaseContext(base)
        }
    }

    override fun onCreate(application: Application) {
        this.mApplication = application
        mGlobalConfig = initModuleConfig(application, mModules!!)
        mGlobalConfig!!.initEnv()

        //初始化YDL第三方依赖
        YdlRepository.initApp(application,mGlobalConfig?.appDebug?:false)

        //执行 扩展的 App onCreate 逻辑
        for (lifecycle in mAppLifecycles!!) {
            lifecycle.onCreate(mApplication!!)
        }

        //注册实现的 RxLifecycle 逻辑
        mApplication!!.registerActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle)


    }

    /**
     * 初始化模块配置
     */
    private fun initModuleConfig(context: Context, modules: List<IConfigModule>): GlobalConfig {
        val builder = GlobalConfig
            .builder()

        //遍历 IConfigModule 集合, 给全局配置 GlobalConfigModule 添加参数
        for (module in modules) {
            module.applyOptions(context, builder)
        }

        return builder.build()
    }
    override fun onTerminate(application: Application) {
        mApplication!!.unregisterActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle)
        if (mAppLifecycles != null && mAppLifecycles!!.size > 0) {
            for (lifecycle in mAppLifecycles!!) {
                lifecycle.onTerminate(mApplication!!)
            }
        }
        this.mAppLifecycles = null
        this.mApplication = null
    }

    override fun getGlobalConfig(): GlobalConfig {
        return mGlobalConfig!!
    }

}

