package com.postgres.util.cmd;

import java.util.*;

class CmdProcessor {

    private static final  boolean DEBUG= false;
	// -- Args as passed into application
	private String args[] = null;
	// -- All arg types we will process. Must be derived from GenericCmd.
	private Vector vArgs = new Vector();
	// -- Adds one argument type for when we process
	protected void add(GenericCmd arg) {
        if (DEBUG) System.out.println("CmdProcessor::add arg.argID="+arg.argID);
		vArgs.addElement(arg);
	}
	// -- Look for an argument type that matches the passed-in target
	protected GenericCmd getArg(String argTarget) {
		Enumeration allArgs  = vArgs.elements();
		GenericCmd foundArg = null;
        if (DEBUG) System.out.println("CmdProcessor::getArg (10) foundArg=" + foundArg);
		// -- Loop through each arg type until we find a match or there are
		// -- no more arg types.
		while (foundArg==null && allArgs.hasMoreElements()) {
			GenericCmd testArg = (GenericCmd)allArgs.nextElement();
            if (DEBUG) System.out.println("CmdProcessor::getArg before argTarget="+argTarget+"; argTarget" + argTarget);
			if (testArg.argID.equalsIgnoreCase(argTarget)) {
                if (DEBUG) System.out.println("CmdProcessor::getArg after argTarget="+argTarget+"; argTarget" + argTarget);
				foundArg =  testArg;
            }
		}
        if (DEBUG) System.out.println("CmdProcessor::getArg before return foundArg=" + foundArg);
		return foundArg;
	}
	// -- Constructor. Hang on to the arguments for when we need to
	// -- process them later.
	protected CmdProcessor(String args[]) {
		this.args = args;
	}
	// -- Process the args that were passed into the application and store
	// -- the results back in the argument types passed into the add method
	protected Hashtable process() throws Exception {
		int iArgIndex = 0;
		Hashtable hArgs = new Hashtable();
		
		while (iArgIndex < args.length) {
			String thisArg = args[iArgIndex++];
            if (DEBUG) System.out.println("CmdProcessor::process (1) thisArg="+thisArg);
			GenericCmd arg = getArg(thisArg);

			if (arg != null) {
                if (DEBUG) System.out.println("CmdProcessor::process thisArg="+thisArg+"; arg.argID=" + arg.argID);
				iArgIndex = arg.set(args, iArgIndex);
				hArgs.put(thisArg, (Object)arg);
			}
		}
		return hArgs;
	}
}
