package de.softwareapp_hb.privateqrscanner

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultRegistryOwner
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleApplier
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleCatalog
import de.softwareapp_hb.privateqrscanner.ui.CleanScannerAppRoot
import de.softwareapp_hb.privateqrscanner.ui.theme.CleanScannerTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val container = (application as CleanScannerApp).appContainer
        setContent {
            PrivateQrLocalizedContent(container, activityResultRegistryOwner = this)
        }
    }
}

@Composable
private fun PrivateQrLocalizedContent(
    container: AppContainer,
    activityResultRegistryOwner: ActivityResultRegistryOwner
) {
    val baseContext = LocalContext.current
    val localeOptions = remember(baseContext.applicationContext) {
        AppLocaleCatalog.load(baseContext.applicationContext)
    }
    val selectedLanguageTag by container.settingsRepository.appLanguageTag.collectAsStateWithLifecycle(
        initialValue = AppLocaleCatalog.SYSTEM_STORAGE_TAG
    )
    val resolvedLanguageTag = AppLocaleCatalog.resolveLanguageTag(localeOptions, selectedLanguageTag)

    LaunchedEffect(baseContext, resolvedLanguageTag) {
        AppLocaleApplier.applyFrameworkAppLocale(baseContext.applicationContext, resolvedLanguageTag)
    }

    val localizedContext = remember(baseContext, resolvedLanguageTag) {
        AppLocaleApplier.wrapContext(baseContext, resolvedLanguageTag)
    }

    CompositionLocalProvider(
        LocalActivityResultRegistryOwner provides activityResultRegistryOwner,
        LocalContext provides localizedContext,
        LocalConfiguration provides localizedContext.resources.configuration
    ) {
        CleanScannerTheme {
            Surface(color = MaterialTheme.colorScheme.background) {
                CleanScannerAppRoot(container, localeOptions)
            }
        }
    }
}
