Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit ad39b2ec authored by Fahim M. Choudhury's avatar Fahim M. Choudhury Committed by Fahim M. Choudhury
Browse files

refactor(settings): improve source selection code for better readability

parent 69a90a29
Loading
Loading
Loading
Loading
Loading
+38 −21
Original line number Diff line number Diff line
@@ -154,29 +154,46 @@ class SettingsFragment : PreferenceFragmentCompat() {
     */
    private val sourceCheckboxListener =
        OnPreferenceChangeListener { preference: Preference, newValue: Any? ->
            val otherBoxesChecked =
                allSourceCheckboxes.filter { it != preference }.any { it?.isChecked == true }
            val isChecked = newValue == true

            if (newValue == false && !otherBoxesChecked) {
                (preference as CheckBoxPreference).isChecked = true
            if (!isChecked && isOnlyRemainingSourceChecked(preference)) {
                showOnlyRemainingSourceWarning(preference)
                return@OnPreferenceChangeListener false
            }

            applySourceChange(preference, isChecked)
            true
        }

    private fun isOnlyRemainingSourceChecked(preference: Preference): Boolean {
        return allSourceCheckboxes
            .filter { it != preference }
            .none { it?.isChecked == true }
    }

    private fun showOnlyRemainingSourceWarning(preference: Preference) {
        (preference as? CheckBoxPreference)?.isChecked = true
        Toast.makeText(
            requireActivity(),
            R.string.select_one_source_of_applications,
            Toast.LENGTH_SHORT
        ).show()

                false
            } else {
                when (preference.key) {
                    Constants.PREFERENCE_SHOW_GPLAY -> updateStore(Source.PLAY_STORE, newValue == true)
                    Constants.PREFERENCE_SHOW_FOSS -> updateStore(Source.OPEN_SOURCE, newValue == true)
                    Constants.PREFERENCE_SHOW_PWA -> updateStore(Source.PWA, newValue == true)
    }

    private fun applySourceChange(preference: Preference, isEnabled: Boolean) {
        val sourceMap = mapOf(
            Constants.PREFERENCE_SHOW_GPLAY to Source.PLAY_STORE,
            Constants.PREFERENCE_SHOW_FOSS to Source.OPEN_SOURCE,
            Constants.PREFERENCE_SHOW_PWA to Source.PWA
        )

        val source = sourceMap[preference.key]
            ?: error("No Source mapping found for preference key: ${preference.key}")

        updateStore(source, isEnabled)

        sourcesChangedFlag = true
        loginViewModel.authObjects.value = null

                true
            }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {