package lan.my.zooty.andyscan;

import android.preference.PreferenceActivity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.ListPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.os.Bundle;

public class AndyScanPrefsActivity
   extends PreferenceActivity 
      implements OnSharedPreferenceChangeListener {

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

      addPreferencesFromResource(R.xml.prefs);
      initSummaries(getPreferenceScreen());
      getPreferenceScreen().getSharedPreferences().
         registerOnSharedPreferenceChangeListener(this);
   }

   private void initSummaries(PreferenceGroup pg) {
      for (int i = 0; i < pg.getPreferenceCount(); ++i) {
         Preference p = pg.getPreference(i);
         if (p instanceof PreferenceGroup) {
            initSummaries((PreferenceGroup) p); // recursion
         } else {
            setSummary(p);
         }
      }
   }

   private void setSummary(Preference pref) {
      if (pref instanceof ListPreference) {
         ListPreference listPref = (ListPreference) pref;
         pref.setSummary(listPref.getEntry());
      } else if (pref instanceof EditTextPreference) {
         EditTextPreference editPref = (EditTextPreference) pref;
         pref.setSummary(editPref.getText());
      }
   }

   public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
      Preference pref = findPreference(key);
      setSummary(pref);
   }
}
