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.Settings
import xyz.myachin.saveto.ui.share.direct.DirectShareActivity
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

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

            setMarketPref()
            setDirectSavingFeature()
            setManualSavingFeature()
        }

        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
                        )
                        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
                        )
                        true
                    } else false
                }
        }
    }
}