package com.mobiuz.app.dev.app

import android.content.Context
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.mobiuz.app.BuildConfig
import com.mobiuz.app.dev.utils.LocaleHelper
import dagger.hilt.android.HiltAndroidApp
import ru.terrakok.cicerone.Router
import timber.log.Timber
import toothpick.Toothpick
import toothpick.configuration.Configuration
import uz.agr.mobiuz.AGRBilling
import uz.agr.mobiuz.di.AppModule
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.FlowNavigationModule
import uz.agr.sdk.coreui.di.ServerModule

@HiltAndroidApp
class App : MultiDexApplication() {

    override fun onCreate() {
        super.onCreate()
        initToothpick()
        initAppScope()
        initLogger()
        AGRBilling.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())
    }
}