package partisan.weforge.xyz.pulse

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.materialswitch.MaterialSwitch

class RedirectSettingsFragment : Fragment() {

    private lateinit var prefs: Preferences

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        prefs = Preferences(requireContext())
        return inflater.inflate(R.layout.fragment_redirect_settings, container, false)
    }

    override fun onResume() {
        super.onResume()
        (requireActivity() as? MainActivity)?.setAppBarTitle(
            getString(R.string.settings_name), getString(R.string.redirect_name)
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val switchWifi = view.findViewById<MaterialSwitch>(R.id.switchRedirectWifi)
        val switchData = view.findViewById<MaterialSwitch>(R.id.switchRedirectData)
        val switchInternational = view.findViewById<MaterialSwitch>(R.id.switchRedirectInternational)
        val switchRoaming = view.findViewById<MaterialSwitch>(R.id.switchRedirectRoaming)

        // Load saved state
        switchWifi.isChecked = prefs.redirectOnWifi
        switchData.isChecked = prefs.redirectOnData
        switchInternational.isChecked = prefs.redirectInternationalOnly
        switchRoaming.isChecked = prefs.redirectIfRoaming

        // Save on toggle
        switchWifi.setOnCheckedChangeListener { _, isChecked ->
            prefs.redirectOnWifi = isChecked
        }
        switchData.setOnCheckedChangeListener { _, isChecked ->
            prefs.redirectOnData = isChecked
        }
        switchInternational.setOnCheckedChangeListener { _, isChecked ->
            prefs.redirectInternationalOnly = isChecked
        }
        switchRoaming.setOnCheckedChangeListener { _, isChecked ->
            prefs.redirectIfRoaming = isChecked
        }
    }
}
