/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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 EditorPreferences editorprefs = 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;
	}
	
	public EditorPreferences getEditorPrefs() {
		return editorprefs;
	}

	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);
		
		prefstring = prefs.get(EditorPreferences.TAG, "");
		if(prefstring.length() == 0)
			editorprefs = new EditorPreferences();
		else
			editorprefs = converter.fromJson(prefstring, EditorPreferences.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));
		prefs.put(EditorPreferences.TAG, converter.toJson(editorprefs));
		
		return true;
	}
	
	/** Applies all changes to preferences to the currently running instance
	 * 
	 */
	public void apply() {
		uiprefs.apply();
		pluginprefs.apply();
		editorprefs.apply();
	}
}
