# SettingsFragment.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.main.more.settings

    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.view.WindowManager
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.viewModels
    import androidx.navigation.fragment.findNavController
    import androidx.viewbinding.ViewBinding
    import com.commonsense.android.kotlin.system.extensions.onBackPressed
    import com.commonsense.android.kotlin.system.extensions.startActivity
    import dagger.hilt.android.AndroidEntryPoint
    import dk.nsp.domain.SettingSubSectionUrl
    import dk.nsp.mingraviditet.BuildConfig
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.databinding.FragmentSettingsBinding
    import dk.nsp.mingraviditet.databinding.SettingsAboutTheAppSectionBinding
    import dk.nsp.mingraviditet.databinding.SettingsPrivacySectionBinding
    import dk.nsp.mingraviditet.databinding.SettingsSecuritySectionBinding
    import dk.nsp.mingraviditet.ui.main.MainActivity
    import dk.nsp.mingraviditet.ui.main.common.LogoutViewModel
    import dk.nsp.mingraviditet.ui.main.more.MoreSection
    import dk.nsp.mingraviditet.ui.useradmission.UserAdmissionActivity
    import dk.nsp.mingraviditet.ui.widgets.HeaderViewWithIconBindingModel
    import dk.nsp.mingraviditet.util.extensions.navigateSafe

    @AndroidEntryPoint
    class SettingsFragment : Fragment() {

        private val vm by viewModels<SettingsViewModel>()
        private val logoutViewModel by viewModels<LogoutViewModel>()

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            val binding = FragmentSettingsBinding.inflate(inflater, container, false)
            binding.toolbar.setNavigationOnClickListener { onBackPressed() }
            binding.toolbar.setTitle(R.string.more_settings_title)

            binding.headerModel = HeaderViewWithIconBindingModel(
                MoreSection.Settings.getTitle(),
                MoreSection.Settings.getDescription(),
                MoreSection.Settings.getIcon()
            )

            binding.apply {
                setupPrivacySection(privacySection)
                setupSecuritySection(securitySection)
                setupAboutTheApp(aboutTheAppSection)
                setupLogoutAndVersion(this)
            }

            return binding.root
        }

        private fun setupPrivacySection(binding: SettingsPrivacySectionBinding) = binding.apply {
            masterData.apply {
                bindViewOnClickToNavigateToUrl(
                    this,
                    SettingSubSectionUrl.MasterData,
                    R.string.settings_master_data_title
                )
            }

            myLog.apply {
                bindViewOnClickToNavigateToUrl(
                    this,
                    SettingSubSectionUrl.MyLog,
                    R.string.settings_my_log_title
                )
            }

            myBlocking.apply {
                bindViewOnClickToNavigateToUrl(
                    this,
                    SettingSubSectionUrl.MyBlocking,
                    R.string.settings_my_locking_title
                )
            }

            privacy.apply {
                bindViewOnClickToNavigateToUrl(
                    this,
                    SettingSubSectionUrl.Privacy,
                    R.string.settings_privacy_title
                )
            }

        }

        private fun bindViewOnClickToNavigateToUrl(
            binding: ViewBinding,
            subSection: SettingSubSectionUrl,
            title: Int
        ) {
            binding.root.setOnClickListener {
                findNavController().navigateSafe(
                    SettingsFragmentDirections.actionSettingsFragmentToWebViewFragment(
                        subSection, title
                    )
                )
            }
        }

        private fun setupSecuritySection(binding: SettingsSecuritySectionBinding) {
            binding.apply {
                biometric.apply {
                    toggled = vm.biometricChecked

                    toggle.isEnabled = vm.biometricEnabled
                    subtitle =
                        if (!vm.biometricEnabled) R.string.login_use_biometrics_after_login else null

                    this.root.post {
                        toggle.setOnCheckedChangeListener { _, checked ->
                            vm.toggleBiometrics(checked)

                            if (checked) {
                                vm.biometricEnabled = false
                                toggle.isEnabled = false

                                subtitle = R.string.login_use_biometrics_after_login
                            }
                        }
                    }
                }

                screenSecurity.apply {
                    toggled = vm.allowScreenshots()

                    root.post {
                        toggle.setOnCheckedChangeListener { _, allowScreenshots ->
                            vm.toggleScreenSecurity(allowScreenshots)

                            if (allowScreenshots) {
                                (activity as? MainActivity)?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
                            } else {
                                (activity as? MainActivity)?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
                            }
                        }
                    }
                }
            }
        }

        private fun setupAboutTheApp(binding: SettingsAboutTheAppSectionBinding) {
            binding.apply {
                bindViewOnClickToNavigateToUrl(
                    aboutTheApp,
                    SettingSubSectionUrl.AboutTheApp,
                    R.string.settings_about_the_app_title
                )

                bindViewOnClickToNavigateToUrl(
                    whoIsBehindTheApp,
                    SettingSubSectionUrl.WhoIsBehindTheApp,
                    R.string.settings_who_is_behind_the_app_title
                )

                consent.root.setOnClickListener {
                    findNavController().navigateSafe(
                        SettingsFragmentDirections.actionSettingsFragmentToConsentFragment()
                    )
                }
            }
        }

        private fun setupLogoutAndVersion(binding: FragmentSettingsBinding) {
            binding.logout.setOnClickListener {
                logoutViewModel.logout()

                activity?.startActivity(UserAdmissionActivity::class.java)
                activity?.finishAffinity()
            }

            binding.versionLabel.text =
                getString(
                    R.string.settings_version,
                    BuildConfig.VERSION_NAME,
                    BuildConfig.VERSION_CODE.toString()
                )
        }
    }