package jp.hasc.loggerserver.handlers;

import java.util.Iterator;

import jp.hasc.loggerserver.HascLoggerServer;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFolder;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * 
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
@SuppressWarnings("unchecked")
public class StartServerHandler extends AbstractHandler {
	/**
	 * The constructor.
	 */
	public StartServerHandler() {
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil
				.getActiveWorkbenchWindowChecked(event);
		try {

			ISelection selection = HandlerUtil.getCurrentSelection(event);
			IFolder f = null;
			if (selection instanceof StructuredSelection) {
				StructuredSelection ss = (StructuredSelection) selection;
				for (Iterator<Object> it = ss.iterator(); it.hasNext();) {
					Object item = it.next();
					if (item instanceof IFolder) {
						f = (IFolder) item;
					}
				}
			}
			String dialogMessage;
			if (HascLoggerServer.server == null) {// server は静止しているか？
				if (f == null) {// フォルダを指定すべし
					showMessage(
							window.getShell(),
							Messages.StartServerHandler_SelectDataFolder);
					return null;
				}
				InputDialog dlg = new InputDialog(window.getShell(),
						Messages.StartServerHandler_PluginLabel, Messages.StartServerHandler_TCPPortNumber,
						Integer.toString(HascLoggerServer.portNum), null);
				if (dlg.open() != Dialog.OK)
					return null;
				HascLoggerServer.portNum = Integer.parseInt(dlg.getValue());
				dialogMessage = Messages.StartServerHandler_StartServer;

			} else { // サーバは稼働中なので、停止すべし
				dialogMessage = Messages.StartServerHandler_StopServer;
			}

			HascLoggerServer.toggleServer(f);
			showMessage(window.getShell(), dialogMessage);

			return null;
		} catch (Exception ex) {
			showMessage(window.getShell(), ex.toString());
			return null;
		}
	}

	private void showMessage(Shell shell, String dialogMessage) {
		MessageDialog.openInformation(shell, Messages.StartServerHandler_PluginLabel,
				dialogMessage);
	}
}
