# AgreementBottomSheetDialog.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.onboarding

    import android.annotation.SuppressLint
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.MotionEvent
    import android.view.View
    import androidx.annotation.MainThread
    import androidx.fragment.app.viewModels
    import androidx.navigation.fragment.findNavController
    import com.commonsense.android.kotlin.views.extensions.gone
    import com.commonsense.android.kotlin.views.extensions.visible
    import dagger.hilt.android.AndroidEntryPoint
    import dk.nsp.domain.SettingSubSectionUrl
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.databinding.FragmentAgreementBottomSheetBinding
    import dk.nsp.mingraviditet.ui.main.more.settings.SettingsPageViewModel
    import dk.nsp.mingraviditet.ui.widgets.BottomSheetViewModel
    import dk.nsp.mingraviditet.ui.widgets.DefaultBottomSheetDialog
    import dk.nsp.mingraviditet.util.android.OpenExternalLinksInBrowserWebViewClient
    import dk.nsp.mingraviditet.util.android.WebViewHelper
    import dk.nsp.mingraviditet.util.android.WebViewHelper.setUpDarkModeSupport
    import dk.nsp.mingraviditet.util.extensions.navigateSafe
    import dk.nsp.util.textmodel.TextModel

    @AndroidEntryPoint
    class AgreementBottomSheetDialog : DefaultBottomSheetDialog() {

        private val targetBaseUrl = "file:///android_asset/"

        override val viewModel: BottomSheetViewModel =
            BottomSheetViewModel(TextModel.from(R.string.agreement_title))

        override val forceFullscreen: Boolean = true

        private val webViewViewModel by viewModels<SettingsPageViewModel>()

        private var agreementBinding: FragmentAgreementBottomSheetBinding? = null

        private var isAgreeButtonEnabled = true
            @MainThread
            set(value) {
                field = value
                agreementBinding?.agreeButton?.isEnabled = value
            }

        @SuppressLint("ClickableViewAccessibility")
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            agreementBinding =
                FragmentAgreementBottomSheetBinding.inflate(
                    LayoutInflater.from(context),
                    binding.scrollView,
                    true
                ).apply {

                    webView.webViewClient =
                        OpenExternalLinksInBrowserWebViewClient(
                            binding.root.context,
                            ::onWebViewPageFinished
                        )

                    webView.setUpDarkModeSupport()
                    webView.setOnTouchListener { _, event -> (event?.action == MotionEvent.ACTION_MOVE) }

                    agreeButton.setOnClickListener {
                        if (isAgreeButtonEnabled) {
                            isAgreeButtonEnabled = false
                            findNavController().navigateSafe(AgreementBottomSheetDialogDirections.actionAgreementBottomSheetDialogToRegistrationFragment())
                        }
                    }
                }
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            webViewViewModel.setPage(SettingSubSectionUrl.Consent)

            webViewViewModel.onErrorLoadingUrl.observe(viewLifecycleOwner) {
                agreementBinding?.loadingSpinner?.root?.gone()
                agreementBinding?.agreeButton?.gone()

                agreementBinding?.errorState?.apply {
                    root.visible()

                    titleText = TextModel.from(R.string.common_alert_title_error)
                    descriptionText = TextModel.from(R.string.common_alert_message_failed_to_load_data)
                }
            }

            webViewViewModel.onContent.observe(viewLifecycleOwner) {
                val htmlToLoad = WebViewHelper.createHtmlWithStyleSheet(it, binding.root.context)

                agreementBinding?.webView?.loadDataWithBaseURL(
                    targetBaseUrl,
                    htmlToLoad,
                    "text/html",
                    "UTF-8",
                    ""
                )
            }
        }

        private fun onWebViewPageFinished(url: String?) {
            if (url?.startsWith(targetBaseUrl) == true) {
                agreementBinding?.loadingSpinner?.root?.gone()
                agreementBinding?.agreeButton?.visible()
            }
        }
    }