package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.text.InputType
import android.widget.EditText
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.utils.ValidateUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.google.android.material.snackbar.Snackbar

class SettingsFragment : PreferenceFragmentCompat(), EditTextPreference.OnBindEditTextListener, Preference.OnPreferenceChangeListener {

    private val snackbar: Snackbar by lazy { Snackbar.make(requireView(), R.string.blank, 4000) }

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

        setNumberInput(SPKeys.SERVER_PORT_BASE)
        setNumberInput(SPKeys.SERVER_PORT_TRX)
        setNumberInput(SPKeys.SERVER_PORT_CONFIG)
        setNumberInput(SPKeys.MIDDLE_PORT)
        setNumberInput(SPKeys.MIDDLE_WORKSTATION_ID)
        setNumberInput(SPKeys.FUEL_PORT)
        setValidate(SPKeys.FUEL_IP)
        setValidate(SPKeys.MIDDLE_IP)
        setValidate(SPKeys.SERVER_DOMAIN)

        DFSLog.i("view = $view", "listView = $listView")
    }

    override fun onBindEditText(editText: EditText) {
        editText.inputType = InputType.TYPE_CLASS_NUMBER
    }

    override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
        val value = newValue.toString()
        val result = when (preference?.key) {
            SPKeys.SERVER_PORT_BASE,
            SPKeys.SERVER_PORT_TRX,
            SPKeys.SERVER_PORT_CONFIG,
            SPKeys.MIDDLE_PORT,
            SPKeys.MIDDLE_WORKSTATION_ID,
            SPKeys.FUEL_PORT -> ValidateUtil.isPositiveInt(value)
            SPKeys.FUEL_IP,
            SPKeys.MIDDLE_IP -> ValidateUtil.isIP(value)
            SPKeys.SERVER_DOMAIN -> ValidateUtil.isUrl(value)
            else -> false
        }
        if (!result) snackbar.setText(R.string.input_not_right).show()
        return result
    }

    private fun setNumberInput(key: String): EditTextPreference? {
        val fragment = this@SettingsFragment
        return findPreference<EditTextPreference>(key)?.apply {
            setOnBindEditTextListener(fragment)
            onPreferenceChangeListener = fragment
        }
    }

    private fun setValidate(key: String) {
        val fragment = this@SettingsFragment
        findPreference<EditTextPreference>(key)?.apply {
            onPreferenceChangeListener = fragment
        }
    }
}
