package com.approximatrix.draco.application.preferences;

import java.util.prefs.Preferences;

import com.google.gson.Gson;

public class PreferencesManager {
	
	private static final String NODE_NAME = "approximatrix.draco";

	private UIPreferences uiprefs = null;
	private PluginPreferences pluginprefs = null;
	
	private Preferences prefs = null;
	
	/** Initializes the preferences manager.  Attempts to load the preferences
	 * from the java preferences system.  If unavailable, defaults are applied.
	 */
	public PreferencesManager() {
		prefs = Preferences.userRoot().node(NODE_NAME); //this.getClass().getName());
		
		initialize();
	}
	
	public UIPreferences getUIPrefs() {
		return uiprefs;
	}

	public PluginPreferences getPluginPrefs() {
		return pluginprefs;
	}

	private void initialize() {
		Gson converter = new Gson();
		
		String prefstring = prefs.get(UIPreferences.TAG, "");
		if(prefstring.length() == 0)
			uiprefs = new UIPreferences();
		else
			uiprefs = converter.fromJson(prefstring, UIPreferences.class);
		
		prefstring = prefs.get(PluginPreferences.TAG, "");
		if(prefstring.length() == 0)
			pluginprefs = new PluginPreferences();
		else
			pluginprefs = converter.fromJson(prefstring, PluginPreferences.class);
		
	}
	
	/** Writes out the preferences to the java preferences system
	 * 
	 * @return true if successful
	 */
	public boolean save() {
				
		Gson converter = new Gson();
		
		prefs.put(UIPreferences.TAG, converter.toJson(uiprefs));
		prefs.put(PluginPreferences.TAG, converter.toJson(pluginprefs));
		
		return true;
	}
	
	/** Applies all changes to preferences to the currently running instance
	 * 
	 */
	public void apply() {
		uiprefs.apply();
		pluginprefs.apply();
	}
}
