package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.text.InputType
import android.widget.EditText
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys

class SettingsFragment : 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)
    }

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

    override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
        val inputValue = newValue.toString()
        DFSLog.i("${preference.key} = $inputValue")
        return true
    }

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

    class PortValidator(private val preference: Preference) : LifecycleObserver, Preference.OnPreferenceChangeListener {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun listen() {
            preference.onPreferenceChangeListener = this
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun remove() {
            preference.onPreferenceChangeListener = null
        }

        override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
            return true
        }
    }
}
