package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.text.InputType
import android.widget.EditText
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.ValidateUtil
import com.doverfuelingsolutions.issp.utils.sp.SPKeys

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

    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)
    }

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

    override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
        if (preference == null || newValue == null) return false

        val value = newValue.toString()
        val key = preference.key
        val result = when (key) {
            SPKeys.SERVER_PORT_BASE,
            SPKeys.SERVER_PORT_TRX,
            SPKeys.SERVER_PORT_CONFIG,
            SPKeys.MIDDLE_PORT,
            SPKeys.MIDDLE_WORKSTATION_ID,
            SPKeys.FUEL_PORT -> ValidateUtil.isPort(value)
            SPKeys.FUEL_IP,
            SPKeys.MIDDLE_IP -> ValidateUtil.isIP(value)
            SPKeys.SERVER_DOMAIN -> ValidateUtil.isUrl(value)
            else -> false
        }
        if (!result) {
            Toast.makeText(requireContext(), StringUtil.get(R.string.input_not_right), Toast.LENGTH_LONG).show()
        }
        return result
    }

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

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