/*
 * $Id: domainnames.java,v 1.1 2005/09/28 16:13:56 rampil Exp $
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2005 satoshi akabane(akabane@logical-paradox.org)
 *
 */
package org.logical_paradox.vsan.tools.console.command;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.rmi.RemoteException;

import org.logical_paradox.shell.Argument;
import org.logical_paradox.shell.Command;
import org.logical_paradox.shell.Option;
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.domain.DomainController;
import org.logical_paradox.vsan.lookup.LookupException;
import org.logical_paradox.vsan.lookup.LookupFactory;
import org.logical_paradox.vsan.tools.console.DacConsoleConstant;

/**
 * <pre>
 * ■domainnames
 * 
 * 【動作仕様】
 * ドメインコントローラーで定義されているドメイン名のリストを返します。
 * 
 * 【書式】
 * domainnames [<ドメインコントローラー]>
 * 
 * 【例】
 * </pre>
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version $Revision: 1.1 $
 */
public class domainnames implements Command {
	public static final String USAGE = "domainnames [<domain controller>]";

	public String usage() {
		return USAGE;
	}

	public ResultCode execute(OutputStream o, ShellEnv env, Argument a) throws CommandExecutionException, TerminationException {
		if(a == null) {
			a = new Argument();
		}
		String[] args = a.getArguments();
		Option[] opts = (Option[])a.getOptions();

		if(args.length > 1 || opts.length > 0) {
			// 引数の数が不正
			throw new CommandExecutionException();
		}

		String dci = null;
		if(args.length == 0) {
			// ドメインコントローラー指定なしの場合
			dci = env.getProperty(DacConsoleConstant.ENV_DC);
			if(dci == null) {
				throw new CommandExecutionException("no domain controller id is specified.");
			}
		} else {
			dci = args[0];
		}

		try {
			// ドメインコントローラーに接続する
			DomainController dc = LookupFactory.getLookup().lookupDomainController(dci);
			// 登録されているドメイン名を取得する
			String[] dn = dc.getDomainNames();

			PrintWriter pw = new PrintWriter(o);

			// レポートの表示
			pw.println("----------------------------------------");
			for(int i = 0; i < dn.length; i++) {
				pw.println((i+1) + " : " + dn[i]);
			}
			pw.println("----------------------------------------");

			pw.println("done.");
			pw.flush();
			pw.close();

		} catch (LookupException e) {
			throw new CommandExecutionException("domain controller seems be down.");
		} catch (RemoteException e) {
			throw new CommandExecutionException("fatal exception has been thrown in retrieving process.");
		}

		return new ResultCode(ResultCode.STATUS_OK);
	}
}
