package jp.hasc.hasctool.ui.commands;

import java.util.Iterator;

import jp.hasc.hasctool.ui.util.UIUtil;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.part.FileEditorInput;

/**
 * @author iwasaki
 */
public class ExecuteBlockDiagramCommand extends AbstractHandler {
	/** logger for this class */
	private final static org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
			.getLog(ExecuteBlockDiagramCommand.class);
	
	public static final String ID_COMMAND="jp.hasc.hasctool.ui.commands.ExecuteBlockDiagramCommand"; //$NON-NLS-1$

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		try{
			IWorkbenchPart part = HandlerUtil.getActivePart(event);
			if (part instanceof IEditorPart) {
				// Editorで編集中のファイルを実行
				IEditorPart te = (IEditorPart) part;
				IEditorInput ei = te.getEditorInput();
				if (ei instanceof FileEditorInput) {
					FileEditorInput fei = (FileEditorInput) ei;
					IFile f = fei.getFile();
					if (f.getName().endsWith(".hascxbd")) { //$NON-NLS-1$
						executeBlockDiagramFile(f, event);
						return null;
					}
				}
			}else if (part instanceof CommonNavigator) {
				// Navigator上での選択されたファイルを実行
				ISelection selection = HandlerUtil.getCurrentSelection(event);
				if (selection instanceof StructuredSelection) {
					StructuredSelection ss = (StructuredSelection) selection;
					for (Iterator<Object> it = ss.iterator(); it.hasNext();) {
						Object item = it.next();
						if (item instanceof IFile) {
							IFile f=(IFile)item;
							executeBlockDiagramFile(f, event);
							return null;
						}
					}
				}
			}    
			
			UIUtil.showMessageDialog(HandlerUtil.getActiveShell(event), Messages.ExecuteBlockDiagramCommand_SelectHascXbdFile);
			return null;
		} catch (Exception ex) {
			LOG.warn("Exception", ex); //$NON-NLS-1$
			UIUtil.showMessageDialog(HandlerUtil.getActiveShell(event), "[Exception]\n" + ex.toString()); //$NON-NLS-1$
		}
		return null;
	}

	private void executeBlockDiagramFile(IFile f, ExecutionEvent event) {
		BlockDiagramExecutorManager m=BlockDiagramExecutorManager.getInstance(event);
		m.executeFile(f);
	}
}
