package com.github.nullptroma.wallenc.app

import android.app.Application
import android.content.Context
import androidx.work.Configuration
import com.github.nullptroma.wallenc.app.di.HiltWorkerFactoryEntryPoint
import com.github.nullptroma.wallenc.app.locale.AppLocaleStorage
import com.github.nullptroma.wallenc.app.sync.StorageSyncBootstrap
import com.github.nullptroma.wallenc.app.tasks.TaskPipelineForegroundBootstrap
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject

@HiltAndroidApp
class WallencApplication : Application(), Configuration.Provider {

    @Inject
    lateinit var taskPipelineForegroundBootstrap: TaskPipelineForegroundBootstrap

    @Inject
    lateinit var storageSyncBootstrap: StorageSyncBootstrap

    override fun attachBaseContext(base: Context) {
        AppLocaleStorage.applyStored(base)
        super.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        AppLocaleStorage.migrateLegacyDataStoreIfNeeded(this)
        AppLocaleStorage.applyStored(this)
        taskPipelineForegroundBootstrap.start()
        storageSyncBootstrap.start()
    }

    override val workManagerConfiguration: Configuration
        get() {
            val factory = EntryPointAccessors.fromApplication(
                applicationContext,
                HiltWorkerFactoryEntryPoint::class.java,
            ).hiltWorkerFactory()
            return Configuration.Builder()
                .setWorkerFactory(factory)
                .build()
        }
}
