package xyz.myachin.saveto.ui.settings

import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import xyz.myachin.saveto.R
import xyz.myachin.saveto.settings.PREVENT_BE_DEFAULT
import xyz.myachin.saveto.settings.Settings
import xyz.myachin.saveto.ui.share.direct.DirectShareActivity
import xyz.myachin.saveto.ui.share.fake.ActionViewActivity
import xyz.myachin.saveto.ui.share.manual.ManualShareActivity

class MainSettingsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.settings_activity)
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings, SettingsFragment())
                .commit()
        }
        supportActionBar?.setDisplayShowHomeEnabled(true)
    }

    class SettingsFragment : PreferenceFragmentCompat() {
        private var directSaving: SwitchPreferenceCompat? = null
        private var manualSaving: SwitchPreferenceCompat? = null
        private var actionView: SwitchPreferenceCompat? = null
        private val actionViewSavingType: SwitchPreferenceCompat by lazy {
            requireNotNull(findPreference("action_view_default"))
        }
        private val monitorDefaultViewer: SwitchPreferenceCompat by lazy {
            requireNotNull(findPreference(PREVENT_BE_DEFAULT))
        }

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)

            setMarketPref()
            setDirectSavingFeature()
            setManualSavingFeature()
            setActionViewFeature()
            setMonitorDefaultViewer()
        }

        private fun setMonitorDefaultViewer() {
            monitorDefaultViewer.setOnPreferenceChangeListener { _, newValue ->
                Settings.preventBeDefault = (newValue as Boolean)
                true
            }
        }

        private fun setActionViewFeature() {
            actionView = findPreference(getString(R.string.process_action_view))

            actionView?.onPreferenceChangeListener =
                Preference.OnPreferenceChangeListener { _, newVal ->
                    val state = when (newVal as Boolean) {
                        true -> PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        false -> PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    }
                    Settings.setComponentState(requireContext().applicationContext,
                        ActionViewActivity::class.java.name,
                        state)
                    true
                }

            actionViewSavingType.setOnPreferenceClickListener {
                if (actionView != null) {
                    Settings.getComponentStateEnabled(requireContext().applicationContext,
                        DirectShareActivity::class.java.name) &&
                            Settings.getComponentStateEnabled(requireContext().applicationContext,
                                ManualShareActivity::class.java.name)
                } else false
            }

            actionViewSavingType.setOnPreferenceChangeListener { _, newValue ->
                Settings.actionViewManual = newValue as Boolean
                true
            }
        }

        private fun setMarketPref() {
            findPreference<Preference>("start_market")?.onPreferenceClickListener =
                Preference.OnPreferenceClickListener {
                    try {
                        startActivity(Intent(Intent.ACTION_VIEW).apply {
                            data = Uri.parse("market://details?id=xyz.myachin.downloader")
                        })
                        true
                    } catch (_: ActivityNotFoundException) {
                        Toast.makeText(requireContext(),
                            R.string.cannot_find_market,
                            Toast.LENGTH_LONG).show()
                        false
                    }
                }
        }

        private fun setManualSavingFeature() {
            manualSaving = findPreference(getString(R.string.allow_manual_saving))
            manualSaving?.onPreferenceChangeListener =
                Preference.OnPreferenceChangeListener { _, newValue ->
                    if (context?.applicationContext != null) {
                        val state = when (newValue as Boolean) {
                            true -> PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                            false -> PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                        }
                        Settings.setComponentState(
                            context?.applicationContext!!,
                            ManualShareActivity::class.java.name, state
                        )
                        setActionViewType()
                        true
                    } else false
                }
        }

        private fun setDirectSavingFeature() {
            directSaving = findPreference(getString(R.string.allow_direct_saving))
            directSaving?.onPreferenceChangeListener =
                Preference.OnPreferenceChangeListener { _, newValue ->
                    if (context?.applicationContext != null) {
                        val state = when (newValue as Boolean) {
                            true -> PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                            false -> {
                                Settings.documentUri = null
                                Settings.archiveUri = null
                                Settings.imageUri = null
                                Settings.videoUri = null
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                            }
                        }
                        Settings.setComponentState(
                            context?.applicationContext!!,
                            DirectShareActivity::class.java.name,
                            state
                        )
                        setActionViewType()
                        true
                    } else false
                }
        }

        private fun setActionViewType() {
            val appContext = requireContext().applicationContext
            val ds =
                Settings.getComponentStateEnabled(appContext, DirectShareActivity::class.java.name)
            val ms =
                Settings.getComponentStateEnabled(appContext, ManualShareActivity::class.java.name)
            when {
                ds && ms -> {
                    actionView?.isEnabled = true
                    actionViewSavingType.isEnabled = true
                }
                !ds && !ms -> {
                    actionView?.isChecked = false
                    actionView?.isEnabled = false
                }
                ds && !ms -> {
                    actionView?.isEnabled = true
                    actionViewSavingType.isChecked = false
                    actionViewSavingType.isEnabled = false
                }
                !ds && ms -> {
                    actionView?.isEnabled = true
                    actionViewSavingType.isChecked = true
                    actionViewSavingType.isEnabled = false
                }
            }
        }
    }
}