package com.remax.visualnovel.configs

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.remax.visualnovel.app.base.app.ApplicationProxy
import com.remax.visualnovel.app.base.app.CommonApplicationProxy
import com.remax.visualnovel.app.initializer.AppInitializersProvider
import com.remax.visualnovel.utils.StatusBarUtils
import com.tencent.mmkv.MMKV
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
import java.lang.ref.WeakReference
import javax.inject.Inject


@HiltAndroidApp
class NovelApplication : MultiDexApplication() {

    companion object {
        private var currentActivity: WeakReference<Activity>? = null

        fun setCurrentActivity(activity: Activity?) {
            currentActivity = if (activity == null) null else WeakReference(activity)
        }

        fun getCurrentActivity(): Activity? {
            return currentActivity?.get()
        }

        private lateinit var instance: NovelApplication
        fun appContext(): Context = instance
    }

    private val proxies = listOf<ApplicationProxy>(CommonApplicationProxy)

    @Inject
    lateinit var appInitializersProvider: AppInitializersProvider

    override fun onCreate() {
        super.onCreate()
        MultiDex.install(this)
        instance = this
        proxies.forEach { it.onCreate(this) }
        appInitializersProvider.startInit()
    }

    override fun onTerminate() {
        MMKV.onExit()
        super.onTerminate()
        proxies.forEach {
            it.onTerminate()
        }
    }

    // 系统资源配置发生更改回调，例如主题模式，需要重新刷新多语言
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        StatusBarUtils.resetNavBarHeight()
        Timber.d("onConfigurationChanged ${newConfig.locales[0]}")
    }

}