# MainActivity.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021-2023 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */
    package dk.nsp.mingraviditet.ui.main

    import android.content.Intent
    import android.os.Bundle
    import androidx.activity.SystemBarStyle
    import androidx.activity.compose.setContent
    import androidx.activity.enableEdgeToEdge
    import androidx.activity.viewModels
    import androidx.compose.foundation.isSystemInDarkTheme
    import androidx.compose.foundation.layout.Box
    import androidx.compose.runtime.Composable
    import androidx.compose.runtime.DisposableEffect
    import androidx.compose.runtime.LaunchedEffect
    import androidx.compose.runtime.getValue
    import androidx.compose.runtime.mutableStateOf
    import androidx.compose.runtime.setValue
    import androidx.compose.ui.res.stringResource
    import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
    import androidx.lifecycle.Lifecycle
    import androidx.lifecycle.LifecycleObserver
    import androidx.lifecycle.compose.LocalLifecycleOwner
    import androidx.lifecycle.lifecycleScope
    import androidx.lifecycle.repeatOnLifecycle
    import dagger.hilt.android.AndroidEntryPoint
    import dk.nsp.mingraviditet.core.authentication.AuthController
    import dk.nsp.mingraviditet.core.designsystem.theme.GravidTheme
    import dk.nsp.mingraviditet.core.shared.R
    import dk.nsp.mingraviditet.feature.authentication.biometricprompt.GravidBiometricPrompt
    import dk.nsp.mingraviditet.ui.BaseActivity
    import kotlinx.coroutines.flow.collect
    import kotlinx.coroutines.flow.onEach
    import kotlinx.coroutines.launch

    @AndroidEntryPoint
    class MainActivity : BaseActivity() {

        private val viewModel: MainActivityViewModel by viewModels()
        private val appTimeoutViewModel by viewModels<AppTimeoutViewModel>()

        override fun onCreate(savedInstanceState: Bundle?) {
            AuthController.getInstance(this.application).configureTIM()
            val splashscreen = installSplashScreen()
            enableEdgeToEdge()

            super.onCreate(savedInstanceState)
            var startDestination: MainActivityUiState by mutableStateOf(MainActivityUiState.Loading)

            lifecycleScope.launch {
                lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    viewModel.startDestination
                        .onEach {
                            it ?: return@onEach
                            startDestination = it
                        }.collect()
                }
            }

            splashscreen.setKeepOnScreenCondition {
                startDestination is MainActivityUiState.Loading
            }

            setContent {
                val darkTheme = isSystemInDarkTheme()

                // Update the edge to edge configuration to match the theme
                // This is the same parameters as the default enableEdgeToEdge call, but we manually
                // resolve whether or not to show dark theme using uiState, since it can be different
                // than the configuration's dark theme value based on the user preference.
                DisposableEffect(darkTheme) {
                    enableEdgeToEdge(
                        statusBarStyle = SystemBarStyle.auto(
                            android.graphics.Color.TRANSPARENT,
                            android.graphics.Color.TRANSPARENT,
                        ) { darkTheme },
                        navigationBarStyle = SystemBarStyle.auto(
                            lightScrim,
                            darkScrim,
                        ) { darkTheme },
                    )
                    onDispose {}
                }

                appTimeoutViewModel.ObserveLifecycleEvents(lifecycle = LocalLifecycleOwner.current.lifecycle)

                var showBiometricPrompt by mutableStateOf(false)

                LaunchedEffect(Unit) {
                    appTimeoutViewModel.logoutEvent.collect {
                        resetApp()
                    }
                }
                LaunchedEffect(Unit) {
                    appTimeoutViewModel.requestAuthenticationEvent.collect {
                        showBiometricPrompt = true
                    }
                }

                GravidTheme(darkTheme = darkTheme) {
                    if (startDestination == MainActivityUiState.Loading) {
                        return@GravidTheme
                    }
                    val startDestination = startDestination.toStartDestination() ?: return@GravidTheme
                    Box {
                        GravidApp(
                            startDestination = startDestination,
                        )
                        GravidBiometricPrompt(
                            showBiometricPrompt = showBiometricPrompt,
                            title = stringResource(R.string.login_with_biometrics),
                            onError = {
                                resetApp()
                            },
                            onSuccess = {
                                appTimeoutViewModel.resetAuthenticationTimer()
                                showBiometricPrompt = false
                            },
                            onDismiss = {
                                resetApp()
                            },
                        )
                    }
                }
            }
        }

        private fun resetApp() {
            finishAffinity()
            startActivity(
                Intent(this, MainActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                },
            )
        }
    }

    @Composable
    fun <viewModel : LifecycleObserver> viewModel.ObserveLifecycleEvents(lifecycle: Lifecycle) {
        DisposableEffect(lifecycle) {
            lifecycle.addObserver(this@ObserveLifecycleEvents)
            onDispose {
                lifecycle.removeObserver(this@ObserveLifecycleEvents)
            }
        }
    }

    /**
     * The default light scrim, as defined by androidx and the platform:
     * https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt;l=35-38;drc=27e7d52e8604a080133e8b842db10c89b4482598
     */
    private val lightScrim = android.graphics.Color.argb(0xe6, 0xFF, 0xFF, 0xFF)

    /**
     * The default dark scrim, as defined by androidx and the platform:
     * https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt;l=40-44;drc=27e7d52e8604a080133e8b842db10c89b4482598
     */
    private val darkScrim = android.graphics.Color.argb(0x00, 0x1b, 0x1b, 0x1b)