package pt.whatsms.gateway

import android.app.Application
import healthModule
import pt.whatsms.gateway.data.dbModule
import pt.whatsms.gateway.modules.connection.connectionModule
import pt.whatsms.gateway.modules.encryption.encryptionModule
import pt.whatsms.gateway.modules.events.eventBusModule
import pt.whatsms.gateway.modules.gateway.GatewayService
import pt.whatsms.gateway.modules.incoming.incomingModule
import pt.whatsms.gateway.modules.localserver.localserverModule
import pt.whatsms.gateway.modules.logs.logsModule
import pt.whatsms.gateway.modules.messages.messagesModule
import pt.whatsms.gateway.modules.notifications.notificationsModule
import pt.whatsms.gateway.modules.orchestrator.OrchestratorService
import pt.whatsms.gateway.modules.orchestrator.orchestratorModule
import pt.whatsms.gateway.modules.ping.pingModule
import pt.whatsms.gateway.modules.receiver.receiverModule
import pt.whatsms.gateway.modules.settings.settingsModule
import pt.whatsms.gateway.modules.webhooks.webhooksModule
import pt.whatsms.gateway.receivers.EventsReceiver
import org.koin.android.ext.android.get
import org.koin.android.ext.android.inject
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin

class App: Application() {
    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidLogger()
            androidContext(this@App)
            modules(
                eventBusModule,
                settingsModule,
                dbModule,
                logsModule,
                notificationsModule,
                messagesModule,
                incomingModule,
                receiverModule,
                encryptionModule,
                pt.whatsms.gateway.modules.gateway.gatewayModule,
                healthModule,
                webhooksModule,
                localserverModule,
                pingModule,
                connectionModule,
                orchestratorModule,
            )
        }

        Thread.setDefaultUncaughtExceptionHandler(
            GlobalExceptionHandler(
                Thread.getDefaultUncaughtExceptionHandler()!!,
                get()
            )
        )

        instance = this

        EventsReceiver.register(this)

        get<OrchestratorService>().start(this, true)
    }

    val gatewayService: GatewayService by inject()

    companion object {
        lateinit var instance: App
            private set
    }
}
