/*
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2005 satoshi akabane(akabane@logical-paradox.org)
 * $Id: dispose.java,v 1.2 2005/09/07 13:38:06 rampil Exp $
 */
package org.logical_paradox.vsan.tools.console.command;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.logical_paradox.shell.Argument;
import org.logical_paradox.shell.Command;
import org.logical_paradox.shell.ResultCode;
import org.logical_paradox.shell.ShellEnv;
import org.logical_paradox.shell.exception.CommandExecutionException;
import org.logical_paradox.shell.exception.TerminationException;
import org.logical_paradox.vsan.dac.Response;
import org.logical_paradox.vsan.dac.ResponseCode;
import org.logical_paradox.vsan.dac.command.Protocol;
import org.logical_paradox.vsan.tools.console.DacConsoleConstant;
import org.logical_paradox.vsan.tools.console.util.SocketWriter;

/**
 * <pre>
 * ■dispose
 * 
 * 【動作仕様】
 * DACに対して、ドメインデータベースの破棄を要求します。
 * このコマンドは、dacコマンドによって設定された'dac'環境変数を参照します。
 * 
 * 【書式】
 * dispose [<hostname>[:<port>]]
 * 
 * </pre>
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version $Revision: 1.2 $
 */
public class dispose implements Command {
	public static final String USAGE = "dispose [<hostname>[:<port>]]";

	public String usage() {
		return USAGE;
	}

	public ResultCode execute(OutputStream o, ShellEnv env, Argument a) throws CommandExecutionException, TerminationException {
		String dac = null;

		if(a == null || a.getArguments().length == 0) {
			dac = env.getProperty(DacConsoleConstant.ENV_DAC);
		} else if(a.getArguments().length > 1) {
			throw new CommandExecutionException();
		} else {
			dac = a.getArguments()[0];
		}
		if(a != null && a.getOptions().length > 0 || a != null && a.getArguments().length > 1) {
			throw new CommandExecutionException();
		}

		try {
			// ドメインデータベースの破棄要求
			PrintWriter pw = new PrintWriter(o);
			pw.println("disposing domain database..\n");

			Response response = SocketWriter.send(dac, new byte[] {(byte)Protocol.P_DISPOSE}, false);

			if(response.getResponseCode() == ResponseCode.OK) {
				pw.println("done.");
				pw.flush();
				pw.close();

				return new ResultCode(ResultCode.STATUS_OK);
			} else {
				// 実行ステータスコードがOK以外の場合
				pw.println("fatal error is caused in executing DISPOSE command: code=[" + response.getResponseCode() + "]\n");
				pw.flush();
				pw.close();

				return new ResultCode(ResultCode.STATUS_ERROR);
			}
		} catch(IOException e) {
			throw new CommandExecutionException(e.getMessage());
		}
	}

}
