package de.sebse.fuplanner.fragments;

import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import de.sebse.fuplanner.R;
import de.sebse.fuplanner.tools.logging.Logger;

public class PrefsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {

    private Logger log = new Logger(this);

    public static PrefsFragment newInstance() {
        PrefsFragment fragment = new PrefsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        // Load the preferences from an XML resource
        setPreferencesFromResource(R.xml.preferences, rootKey);
        for (String s : getPreferenceScreen().getSharedPreferences().getAll().keySet()) {
            onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), s);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
        Preference preference = getPreferenceScreen().findPreference(s);
        if (preference instanceof ListPreference)
            preference.setSummary(((ListPreference) preference).getEntry());
    }
}