package anywheresoftware.b4a.objects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map.Entry;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.keywords.Common;
import anywheresoftware.b4a.objects.collections.List;
import anywheresoftware.b4a.objects.collections.Map;
@Version(1.0f)
public class preferenceactivity extends PreferenceActivity{
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Intent in = getIntent();
      if (in == null || in.hasExtra("preferences") == false) {
         Common.Log("Intent missing root node.");
         return;
      }
      
      PreferenceScreenWrapper p = (PreferenceScreenWrapper) in.getSerializableExtra("preferences");
      PreferenceScreen ps = (PreferenceScreen) p.createPreference(this);
      this.setPreferenceScreen(ps);
      
   }
   /**
    * Provides access to the saved settings. Using PreferenceManager you can get the stored values and modify them.
    */
   @ShortName("PreferenceManager")
   public static class PreferenceManager {
      private SharedPreferences sp = android.preference.PreferenceManager.getDefaultSharedPreferences(BA.applicationContext);
      private HashSet<String> updatedKeys = new HashSet<String>();
      public PreferenceManager() {
         sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(
                  SharedPreferences sharedPreferences, String key) {
               updatedKeys.add(key);
            }
            
         });
      }
      /**
       * PreferenceActivity library allows you to show the standard settings interface and provides an easy way to handle applications settings.
       *This library requires you to modify AndroidManifest.xml. See the <link>tutorial|http://www.b4x.com/forum/basic4android-getting-started-tutorials/10608-preferenceactivity-tutorial.html</link> for more information.
       */
      public static void LIBRARY_DOC() {
         
      }
      /**
       * Returns a list with the keys that were updated since the last call to GetUpdatedKeys.
       *Note that the updated keys may include keys with unchanged values.
       */
      public List GetUpdatedKeys() {
         List l = new List();
         l.Initialize();
         for (String s : updatedKeys) {
            l.Add(s);
         }
         updatedKeys.clear();
         return l;
      }
      /**
       * Returns the String value mapped to the given key. Returns an empty string if the key is not found.
       */
      public String GetString(String Key) {
         return sp.getString(Key, "");
      }
      /**
       * Returns the Boolean value mapped to the given key. Returns False is the key is not found.
       */
      public boolean GetBoolean(String Key) {
         return sp.getBoolean(Key, false);
      }
      /**
       * Returns a Map with all the Keys and Values. Note that changes to this map will not affect the stored values.
       */
      public Map GetAll() {
         Map m = new Map();
         m.Initialize();
         for (Entry<String, ?> e : sp.getAll().entrySet()) {
            m.Put(e.getKey(), e.getValue());
         }
         return m;
      }
      /**
       * Maps the given key to the given String value.
       */
      public void SetString(String Key, String Value) {
         Editor e = sp.edit();
         e.putString(Key, Value);
         e.commit();
      }
      /**
       * Maps the given key to the given Boolean value.
       */
      public void SetBoolean(String Key, boolean Value) {
         Editor e = sp.edit();
         e.putBoolean(Key, Value);
         e.commit();
      }
      /**
       * Clears all stored entries.
       */
      public void ClearAll() {
         Editor e = sp.edit();
         e.clear();
         e.commit();
      }
   }
   /**
    * 
    */
   @ShortName("PreferenceScreen")
   public static class PreferenceScreenWrapper extends B4APreference{
      
      protected ArrayList<B4APreference> childs;
      protected static int randomKey;
      public PreferenceScreenWrapper() {
         this("PreferenceScreen" + Integer.toString(++randomKey));
      }
      protected PreferenceScreenWrapper(String key) {
         super(key, null, null, null);
      }
      /**
       * Initializes the object and sets the title that will show. The summary will show for secondary PreferenceScreens.
       */
      public void Initialize(String Title, String Summary) {
         childs = new ArrayList<B4APreference>();
         this.title = Title;
         this.summary = Summary;
      }
      /**
       * Creates the Intent object that is required for showing the PreferencesActivity.
       *Example:<code>StartActivity(PreferenceScreen1.CreateIntent)</code>
       */
      public Intent CreateIntent() {
         Intent in = new Intent();
         in.setClass(BA.applicationContext, preferenceactivity.class);
         in.putExtra("preferences", this);
         return in;
      }
      @Override
      Preference createPreference(PreferenceActivity c) {
         PreferenceScreen ps = c.getPreferenceManager().createPreferenceScreen(c);
         handleDefaults(ps);
         for (B4APreference b : childs) {
            if (b instanceof PreferenceCategoryWrapper) {
               ((PreferenceCategoryWrapper)b).parent = ps;
               b.createPreference(c);
            }
            else {
               ps.addPreference(b.createPreference(c));
            }
         }
         return ps;
      }
      /**
       * Adds a preference entry with a check box. The entry values can be either True or False.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist.
       */
      public void AddCheckBox(String Key, String Title, String Summary, boolean DefaultValue) {
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               CheckBoxPreference cbp = new CheckBoxPreference(c);
               handleDefaults(cbp);
               return cbp;
            }
         });
      }
      /**
       * Adds a preference entry which allows the user to choose a single item out of a list.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist. Should match one of the values.
       *Values - A list of strings with the possible values.
       */
      public void AddList(String Key, String Title, String Summary, String DefaultValue, List Values) {
         final CharSequence[] values = new String[Values.getSize()];
         for (int i = 0;i < values.length;i++) {
            values[i] = String.valueOf(Values.Get(i));
         }
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               ListPreference list = new ListPreference(c);
               handleDefaults(list);
               list.setDialogTitle(title);
               
               list.setEntries(values);
               list.setEntryValues(values);
               return list;
            }
         });
      }
      /**
       * Adds a preference entry which allows the user to enter free text.
       *Key - The preference key associated with the value.
       *Title - Entry title.
       *Summary - Entry summary (second row).
       *DefaultValue - The default value of this preference entry if the key does not already exist.
       */
      public void AddEditText(String Key, final String Title, final String Summary, final String DefaultValue) {
         childs.add(new B4APreference(Key, Title, Summary, DefaultValue) {
            @Override
            Preference createPreference(PreferenceActivity c) {
               EditTextPreference e = new EditTextPreference(c);
               e.setDialogTitle(title);
               handleDefaults(e);
               return e;
            }
         });
      }
      /**
       * Adds a secondary PreferenceScreen. When the user presses on this entry the second screen will appear.
       */
      public void AddPreferenceScreen(PreferenceScreenWrapper PreferenceScreen) {
         childs.add(PreferenceScreen);
      }
      /**
       * Adds a PreferenceCategory. A preference category is made of a title and a group of entries.
       *Note that a PreferenceCategory cannot hold other PreferenceCategories.
       */
      public void AddPreferenceCategory(PreferenceCategoryWrapper PreferenceCategory) {
         childs.add(PreferenceCategory);
      }
   }
   /**
    * PreferenceCategory holds a group of other preferences.
    */
   @ShortName("PreferenceCategory")
   public static class PreferenceCategoryWrapper extends PreferenceScreenWrapper {
      PreferenceGroup parent;
      public PreferenceCategoryWrapper() {
         super("PreferenceCategory" + Integer.toString(++randomKey));
      }
      /**
       * Initializes the object and sets the category title.
       */
      public void Initialize(String Title) {
         childs = new ArrayList<B4APreference>();
         this.title = Title;
      }
      @Override
      Preference createPreference(PreferenceActivity c) {
         PreferenceCategory pc = new PreferenceCategory(c);
         handleDefaults(pc);
         if (parent == null) {
            Common.Log("Error: PreferenceCategories cannot be nested!");
         }
         parent.addPreference(pc);
         for (B4APreference b : childs) {
            pc.addPreference(b.createPreference(c));
         }
         return pc;
      }
      @Override
      @Hide
      public Intent CreateIntent() {
         return null;
      }
   }
   static abstract class B4APreference implements Serializable{
      String key;
      Serializable defaultValue;
      String title, summary;
      public B4APreference(String key, String title, String summary, Serializable defaultValue) {
         this.key = key;
         this.defaultValue = defaultValue;
         this.summary = summary;
         this.title = title;
      }
      abstract Preference createPreference(PreferenceActivity c) ;
      protected void handleDefaults(Preference p) {
         p.setKey(key);
         p.setDefaultValue(defaultValue);
         p.setTitle(title);
         p.setSummary(summary);
      }
   }
}