# RegistrationFragment.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.app.Activity
    import android.content.Intent
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.activity.result.contract.ActivityResultContracts
    import androidx.annotation.StringRes
    import androidx.appcompat.app.AlertDialog
    import androidx.fragment.app.Fragment
    import androidx.lifecycle.lifecycleScope
    import androidx.navigation.fragment.findNavController
    import dk.nsp.domain.auth.AuthRepo
    import dk.nsp.domain.auth.RegistrationError
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.databinding.FragmentRegistrationBinding
    import dk.nsp.mingraviditet.domain.AlertDialogButtonModel
    import dk.nsp.mingraviditet.domain.AlertDialogViewModel
    import dk.nsp.mingraviditet.util.BundleBooleanDelegate
    import dk.nsp.mingraviditet.util.extensions.createAndShowWith
    import dk.nsp.mingraviditet.util.extensions.isInternetAvailable
    import dk.nsp.mingraviditet.util.extensions.navigateSafe
    import dk.nsp.mingraviditet.util.extensions.popNavBackStack
    import dk.nsp.shared.Failed
    import dk.nsp.shared.Success
    import dk.nsp.shared.util.extensions.debugPrintIntent
    import dk.nsp.shared.util.launchDefault
    import dk.nsp.shared.util.launchMain
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.launch
    import timber.log.Timber

    class RegistrationFragment : Fragment() {
        private val authRepo by lazy {
            context?.let { AuthRepo(it) }
        }

        //This handles when the process gets Emptied and other weird cases where local variables gets cleaned up
        //since arguments in baseFragment gets saved in onInstanceSave
        private var isInFlight by BundleBooleanDelegate(this::getArguments)

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            return FragmentRegistrationBinding.inflate(inflater, container, false).root
        }

        override fun onResume() {
            super.onResume()
            //is added is since we can get here before we are added..
            if (isInFlight != true && isAdded) {
                startOpenIdLogin()
            }
        }

        private val registerCallback =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    handleRegistrationResult(result.data)
                } else {
                    Timber.e(result.data?.debugPrintIntent())
                    handleRegistrationError(RegistrationError.Other)
                }
            }

        private fun startOpenIdLogin() = lifecycleScope.launchDefault {
            val authRepo = authRepo ?: return@launchDefault
            //if we cannot get a context, do not block the login.
            isInFlight = true
            when (val registerIntentRes = authRepo.getRegisterIntent()) {
                is Success -> {
                    registerCallback.launch(registerIntentRes.value)
                }
                is Failed -> launchMain { popNavBackStack() }
            }
        }

        private fun handleRegistrationResult(data: Intent?) = lifecycleScope.launchDefault {
            Timber.d("Got result from Custom Tab Browser: ${data.debugPrintIntent()}")
            val authRepo = authRepo
            if (authRepo == null) {
                Timber.e("Context was null for ${RegistrationFragment::class.simpleName}")
                popNavBackStack()
                return@launchDefault
            }

            // Attempt to setup the AuthRepo from the data received
            authRepo.handleLoginResultAndGetAccessToken(
                scope = this,
                data = data,
                onAccessToken = {
                    CoroutineScope(Dispatchers.Main).launch {
                        findNavController().navigateSafe(
                            RegistrationFragmentDirections.actionRegistrationFragmentToLoginFragment(
                                PinCodeMode.CreatePin
                            )
                        )
                    }
                },
                onFailed = { error ->
                    handleRegistrationError(error)
                }
            )
        }

        private fun handleRegistrationError(error: RegistrationError) {
            if (context?.isInternetAvailable() != true) {
                showRegistrationErrorDialog(
                    R.string.common_alert_title_error,
                    R.string.common_alert_message_failed_to_load_data
                )
                return
            }
            Timber.e("Login failed with error=  {$error}")
            when (error) {
                RegistrationError.UserCanceled -> popNavBackStack()
                RegistrationError.NoUsableBrowserFoundException -> {
                    showRegistrationErrorDialog(
                        R.string.android_login_no_browser_title,
                        R.string.android_login_no_browser_description
                    )
                }
                RegistrationError.Other, RegistrationError.NetworkError -> {
                    showRegistrationErrorDialog(
                        R.string.common_alert_title_error,
                        R.string.common_alert_message_generic
                    )
                }
            }
        }

        private fun showRegistrationErrorDialog(
            @StringRes title: Int,
            @StringRes message: Int
        ) = CoroutineScope(Dispatchers.Main).launch {
            context?.let {
                AlertDialog.Builder(it).createAndShowWith(
                    AlertDialogViewModel(
                        title,
                        message,
                        positiveButton = AlertDialogButtonModel(R.string.common_ok),
                        onDismissListener = {
                            popNavBackStack()
                        }
                    )
                )
            } ?: popNavBackStack()
        }
    }