package de.tudarmstadt.informatik.hostage.ui2.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;

import java.util.HashMap;

import de.tudarmstadt.informatik.hostage.R;

/**
 * @author Alexander Brakowski
 * @created 02.03.14 21:03
 */
public class PreferenceHostageFrament extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
	private HashMap<String, String> mSuffixMap;
	private String[] mTextPreferences;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

		this.mTextPreferences = new String[]{
			"pref_external_location",
			"pref_upload_server",
			"pref_max_connections",
			"pref_timeout",
			"pref_sleeptime",
			"pref_location_time",
			"pref_location_retries"
		};

		this.mSuffixMap = new HashMap<String, String>();
		this.mSuffixMap.put("pref_timeout", "s");
		this.mSuffixMap.put("pref_sleeptime", "ms");
		this.mSuffixMap.put("pref_location_time", "ms");

		addPreferencesFromResource(R.xml.settings_preferences);

		for(String k: this.mTextPreferences){
			updatePreferenceSummary(k);
		}
	}

	private void updatePreferenceSummary(String key){
		Preference p = findPreference(key);
		SharedPreferences sharedPreferences = this.getPreferenceManager().getSharedPreferences();

		if(p != null && p instanceof EditTextPreference){
			String suffix = "";

			if(this.mSuffixMap.containsKey(key)){
				suffix = this.mSuffixMap.get(key);
			}

			p.setSummary(sharedPreferences.getString(key, "") + " " + suffix);
		}
	}

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

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

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		updatePreferenceSummary(key);
	}
}
