/*
 * (c) Copyright Sysdeo SA 2001, 2002.
 * All Rights Reserved.
 */

package com.sysdeo.eclipse.tomcat.actions;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;

import com.sysdeo.eclipse.tomcat.TomcatLauncherPlugin;
import com.sysdeo.eclipse.tomcat.VMLauncherUtility;

/**
 * TomcatKeyHandler
 *
 */
public class TomcatKeyHandler extends AbstractHandler {

	/** START_STOP_CMD_ID */
	private static final String START_STOP_CMD_ID = "pl.szpinda.plugin.tomcat.commands.tomcatStartStop";

	/**
	 * @param arg ExecutionEvent
	 * @return Object
	 */
	@Override
	public Object execute(final ExecutionEvent arg) throws ExecutionException {
		boolean restart = !arg.getCommand().getId().equals(START_STOP_CMD_ID);
		boolean start = false;
		try {
			if (restart) {
				if (VMLauncherUtility.getILaunch() == null || VMLauncherUtility.getILaunch().isTerminated()) {
					TomcatLauncherPlugin.getTomcatBootstrap().start();
				} else {
					VMLauncherUtility.getILaunch().terminate();
					TomcatLauncherPlugin.getTomcatBootstrap().start();
				}
			} else {
				if (VMLauncherUtility.getILaunch() == null || VMLauncherUtility.getILaunch().isTerminated()) {
					start = true;
					TomcatLauncherPlugin.getTomcatBootstrap().start();
				} else {
					VMLauncherUtility.getILaunch().terminate();
				}
			}
		} catch (final CoreException ex) {
			String msg = null;
			if (restart) {
				msg = TomcatLauncherPlugin.getResourceString("msg.restart.failed");
			} else if (start) {
				msg = TomcatLauncherPlugin.getResourceString("msg.start.failed");
			} else {
				msg = TomcatLauncherPlugin.getResourceString("msg.stop.failed");
			}
			TomcatLauncherPlugin.log(msg + "/n");
			TomcatLauncherPlugin.log(ex);
		}
		return null;
	}
}
