# LoginFragment.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021 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.useradmission.login

    import android.os.Build
    import android.os.Bundle
    import android.view.*
    import android.widget.Toast
    import androidx.appcompat.app.AlertDialog
    import androidx.biometric.BiometricPrompt
    import androidx.core.content.ContextCompat
    import androidx.core.view.*
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.viewModels
    import androidx.lifecycle.coroutineScope
    import androidx.navigation.fragment.findNavController
    import androidx.navigation.fragment.navArgs
    import dagger.hilt.android.AndroidEntryPoint
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.databinding.FragmentLoginBinding
    import dk.nsp.mingraviditet.domain.AlertDialogViewModel
    import dk.nsp.mingraviditet.extensions.enabledOrDisabled
    import dk.nsp.mingraviditet.ui.useradmission.login.keyboard.KeyboardViewModel
    import dk.nsp.mingraviditet.ui.widgets.PinCodeInputDelegate
    import dk.nsp.mingraviditet.util.extensions.createAndShowWith
    import dk.nsp.mingraviditet.util.extensions.navigateSafe
    import dk.nsp.mingraviditet.util.extensions.observeIfNotHandled
    import dk.nsp.mingraviditet.util.extensions.safeViewModels
    import dk.nsp.util.TextModel
    import javax.crypto.Cipher

    @AndroidEntryPoint
    class LoginFragment : Fragment() {
        private lateinit var binding: FragmentLoginBinding
        private val keyboardViewModel = KeyboardViewModel()

        private val args: LoginFragmentArgs by navArgs()

        private val initialViewModel: InitialDataFetchViewModel by viewModels()

        private val loginViewModel: LoginViewModel? by safeViewModels {
            activity?.application?.let { application ->
                LoginViewModelFactory(application, args.pinMode, keyboardViewModel)
            }
        }

        private val pinCodeInputDelegate by lazy {
            PinCodeInputDelegate(binding.pinInputFields)
        }

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            binding = FragmentLoginBinding.inflate(LayoutInflater.from(context), container, false)

            binding.loginViewModel = loginViewModel
            binding.keyboardViewModel = keyboardViewModel
            binding.lifecycleOwner = this

            // PinCode events:
            //Loading
            loginViewModel?.doingLogin?.observeIfNotHandled(viewLifecycleOwner) {
                binding.keyboard.keyboardContainer.enabledOrDisabled(false)
                pinCodeInputDelegate.hideAndStartLoading()
            }

            // Error
            loginViewModel?.loginErrorEvent?.observeIfNotHandled(viewLifecycleOwner) {
                resetUI(it)
            }

            keyboardViewModel.onPinChangedListener.observe(viewLifecycleOwner) {
                pinCodeInputDelegate.updatePins(it)
            }

            loginViewModel?.dialogError?.observeIfNotHandled(viewLifecycleOwner, ::showError)

            loginViewModel?.forceNavigateToRegistration?.observeIfNotHandled(viewLifecycleOwner) {
                findNavController().navigateSafe(LoginFragmentDirections.actionLoginFragmentToRegistrationFragment())
            }

            // Login success!
            loginViewModel?.loginSuccessEvent?.observeIfNotHandled(viewLifecycleOwner) {
                initialViewModel.tryInitializeUserData()
            }

            //Data fetching
            initialViewModel.triggerDataFetchFailedDialog.observeIfNotHandled(
                viewLifecycleOwner,
                ::showError
            )
            initialViewModel.successFullyLoadedData.observeIfNotHandled(viewLifecycleOwner) { success ->
                if (success) {
                    findNavController().navigateSafe(LoginFragmentDirections.actionLoginFragmentToMainActivity())
                    activity?.finish()
                } else {
                    resetUI(null)
                    loginViewModel?.setPinMode(PinCodeMode.Login)
                }
            }

            // Bioemtric prompting?
            keyboardViewModel.onBiometricPressed.observeIfNotHandled(viewLifecycleOwner) {
                loginViewModel?.forceBiometricFlow()
            }

            loginViewModel?.triggerBiometricPrompt?.observeIfNotHandled(viewLifecycleOwner) {
                lifecycle.coroutineScope.launchWhenResumed {
                    showBiometricPrompt(it)
                }
            }

            loginViewModel?.basicInfoToast?.observeIfNotHandled(viewLifecycleOwner) {
                val context = context ?: return@observeIfNotHandled
                Toast.makeText(context, it.getString(context.resources), Toast.LENGTH_LONG).show()
            }

            setKeyboardToInsets()

            return binding.root
        }

        private fun resetUI(textModel: TextModel?) {
            pinCodeInputDelegate.animateForError(textModel) {
                keyboardViewModel.clearPin()
            }
            binding.keyboard.keyboardContainer.enabledOrDisabled(true)
        }

        private fun showError(dialogModel: AlertDialogViewModel) {
            context?.let {
                AlertDialog
                    .Builder(it)
                    .createAndShowWith(dialogModel)
            }
        }

        // Set window insets:
        // NOTE: This somehow doesn't work when creating a pin, which is why there is a fallback
        private fun setKeyboardToInsets() {
            val bottomMargin = resources.getDimensionPixelSize(R.dimen.large_spacing)

            if (loginViewModel?.pinCodeMode?.value == PinCodeMode.Login) {
                ViewCompat.setOnApplyWindowInsetsListener(binding.keyboard.root) { v, insets ->
                    val params: ViewGroup.MarginLayoutParams =
                        v.layoutParams as ViewGroup.MarginLayoutParams

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        val navInsets = insets.getInsets(WindowInsets.Type.navigationBars())

                        params.bottomMargin = navInsets.bottom + bottomMargin
                    } else {
                        params.bottomMargin = insets.systemWindowInsetBottom + bottomMargin
                    }

                    insets
                }
            } else {
                // if the phone has a navigation bar
                val hasSoftwareNavigation = !ViewConfiguration.get(context).hasPermanentMenuKey()
                if (hasSoftwareNavigation) {
    //                 Fallback when user is creating pin, as Insets doesn't work here somehow
                    val defaultNavigationBarHeight =
                        resources.getDimensionPixelSize(R.dimen.default_navigation_bar_height)

                    val params = binding.keyboard.root.layoutParams as ViewGroup.MarginLayoutParams
                    params.bottomMargin = bottomMargin + defaultNavigationBarHeight
                }
            }
        }

        private fun showBiometricPrompt(cipher: Cipher) {
            loginViewModel?.let {
                context?.let { context ->
                    val biometricPrompt = BiometricPrompt(
                        this,
                        ContextCompat.getMainExecutor(context),
                        it.biometricPromptCallback
                    )

                    val promptInfo = BiometricPrompt.PromptInfo.Builder()
                        .setTitle(getString(R.string.login_with_biometrics))
                        .setNegativeButtonText(context.getString(R.string.common_cancel))
                        .setConfirmationRequired(it.pinCodeMode.value == PinCodeMode.CreatePin)
                        .build()

                    biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
                }
            }
        }
    }