/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package org.apache.tools.ant.taskdefs.optional.iplanet;

import org.apache.tools.ant.BuildException;

import java.util.Map;
import java.util.HashMap;

public class ComponentTask extends ComponentAdmin {
	private String action;

	private static final String ACTION_ENABLE  = "enable";
	private static final String ACTION_DISABLE = "disable";

	private static final Map ACTION_MAP = new HashMap(2);
	static {
		ACTION_MAP.put(ACTION_ENABLE, "enable");
		ACTION_MAP.put(ACTION_DISABLE, "disable");
	};

	public void setAction(String action) {
		this.action = action;
	}

	protected void checkComponentConfig(Component comp) throws BuildException {
		super.checkComponentConfig(comp);

		if (action == null) {
			String msg = "The action command must be specified.";
			throw new BuildException(msg, getLocation());
		}

		if (!ACTION_MAP.containsKey(action)) {

			String msg = "The action command (\"" + action + "\") is invalid.";
			throw new BuildException(msg, getLocation());
		}

		// name must be valid string
		String theName = comp.getName();
		if ((theName == null) || (theName.length() == 0)) {
			String msg = "The component name (\"" + theName + "\") is not valid";
			throw new BuildException(msg, getLocation());
		}
	}

	protected String getCommandString(Server server, Component comp) {
		StringBuffer cmdString = new StringBuffer();
		cmdString.append(ACTION_MAP.get(action));
		cmdString.append(server.getCommandParameters(true));
		if (comp.getType() != null) {
			cmdString.append(" --type ").append(comp.getType());
		}
		cmdString.append(" ").append(comp.getName());

		return cmdString.toString();
	}
}