package uz.mobiuz.mobiservice.dev.app

import android.content.Context
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
import toothpick.Toothpick
import toothpick.configuration.Configuration
import uz.agr.sdk.core.di.DI
import uz.agr.sdk.core.di.module.CoreServerModule
import uz.agr.sdk.core.model.system.LocaleManager
import uz.agr.sdk.coreui.di.ServerModule
import uz.agr.sdk.pgw_core.mobi.MobiUz
import uz.mobiuz.mobiservice.dev.BuildConfig
import uz.mobiuz.mobiservice.dev.utils.LocaleHelper

@HiltAndroidApp
class App : MultiDexApplication() {

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        initToothpick()
        initAppScope()
        initLogger()
//        AGRBilling.init(this)
        MobiUz.init(this)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(LocaleManager.setLocale(base))
        MultiDex.install(this)
    }

    override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
        super.onConfigurationChanged(newConfig)
        LocaleHelper.setLocale(this)
    }

    private fun initToothpick() {
        if (BuildConfig.DEBUG) {
            Toothpick.setConfiguration(Configuration.forDevelopment().preventMultipleRootScopes())
        } else {
            Toothpick.setConfiguration(Configuration.forProduction())
        }
    }

    private fun initLogger() {
        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }
    }

    private fun initAppScope() {
        val appScope = Toothpick.openScope(DI.APP_SCOPE)
//        appScope.installModules(AppModule())
        appScope.installModules(CoreServerModule("MOBIUZ"))
//        appScope.installModules(FlowNavigationModule(appScope.getInstance(Router::class.java)))

        val serverScope = Toothpick.openScopes(DI.APP_SCOPE, DI.SERVER_SCOPE)
        serverScope.installModules(ServerModule())
    }

    companion object {
        lateinit var INSTANCE: App
    }
}