// PreferencesManager.java
//
// Created: December 2005
//
// This file is a component of the BioMoby project.
// Copyright Martin Senger (martin.senger@gmail.com).
//

import org.biomoby.client.CmdLineHelper;

import org.tulsoft.tools.BaseCmdLine;
import org.tulsoft.shared.PrefsUtils;
import org.tulsoft.shared.UUtils;

import org.apache.commons.lang.StringUtils;

import java.util.prefs.Preferences;
import java.util.prefs.BackingStoreException;

/**
 *
 * @author <A HREF="mailto:senger@ebi.ac.uk">Martin Senger</A>
 * @version $Id: PreferencesManager.java,v 1.1 2009/02/03 06:28:42 senger Exp $
 */

public class PreferencesManager
    extends CmdLineHelper {

    /*************************************************************************
     *
     * Entry point...
     *
     *************************************************************************/
    public static void main (String [] args) {
	try {

	    BaseCmdLine cmd = getCmdLine (args, PreferencesManager.class);
	    String param;
	    String[] params;

	    // -remove <full-node-name>
	    removePreferences (cmd.getParam ("-remove"));

	    // -add <full-node-name> <new-value-for-this-node>
	    params = cmd.getParam ("-add", 2);
	    updatePreference (params[0], params[1]);

	    // -replace <full-node-name> <new-value-for-this-node>
	    params = cmd.getParam ("-replace", 2);
	    removePreferences (params[0]);
	    updatePreference (params[0], params[1]);

	} catch (Throwable e) {
	    processErrorAndExit (e);
	}
    }

    //
    private static void removePreferences (String nodeName)
	throws BackingStoreException {
	if (StringUtils.isBlank (nodeName))
	    return;
	Preferences node = PrefsUtils.getNode (nodeName);
	msgln ("Removing preferences: " + nodeName);
	node.removeNode();
    }

    //
    private static void updatePreference (String nodeName, String nodeValue)
	throws BackingStoreException {
	if (StringUtils.isBlank (nodeName))
	    return;
	Preferences node = PrefsUtils.getNode (nodeName);
	if (nodeValue == null)
	    return;
	msgln (String.format ("Adding preference: %s = %s",
			      nodeName, nodeValue));
	PrefsUtils.updateKey (node, "" + UUtils.unique(), nodeValue);
    }

}
