/*
 * This file has been developed at the University of Munich, Chair for Programming & Software Engineering.
 * 
 * This file is licensed under the Eclipse Public License (EPL) 1.0
 * 
 */
package eu.mdd4soa.trans.end2end.actions;

import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.IAction;
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.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import eu.mdd4soa.smm.statik.Participant;
import eu.mdd4soa.trans.smm2bpel.SMM2BPELPlugin;
import eu.mdd4soa.trans.smm2bpel.actions.ConvertSMM2BpelAction;
import eu.mdd4soa.trans.uml2smm.ui.actions.Convert2SMMAction;

public class UML2WS implements IObjectActionDelegate {

	private IWorkbenchPart fWorkbenchPart;

	private IFile fSelectedFile;

	@Override
	public void run(IAction action) {

		Convert2SMMAction action1= new Convert2SMMAction();
		action1.setActivePart(action, fWorkbenchPart);
		action1.selectionChanged(action, new StructuredSelection(fSelectedFile));
		action1.run(action);
		List<Participant> participants= action1.getParticipants();

		IProject project= fSelectedFile.getProject();
		IFolder bpelFolder= project.getFolder("bpel");

		try {
			if (bpelFolder == null || !bpelFolder.exists())
				bpelFolder.create(true, true, new NullProgressMonitor());

			for (Participant participant : participants) {
				if (!participant.getBehaviours().isEmpty()) {

					ConvertSMM2BpelAction.convertParticipantToWS(bpelFolder, participant);
				}
			}
		} catch (Exception e) {
			SMM2BPELPlugin.logError("Problem converting to WS*", e);
			MessageDialog.openError(getShell(), "UML2WS", "Problem converting to WS*: " + e.getMessage());
		}

	}


	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		fWorkbenchPart= targetPart;
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection == null || ! (selection instanceof StructuredSelection) && ( ((StructuredSelection) selection).isEmpty()))
			fSelectedFile= null;
		else {
			Object element= ((StructuredSelection) selection).getFirstElement();
			if (element instanceof IFile)
				fSelectedFile= (IFile) element;
			else
				fSelectedFile= null;
		}
	}

	private Shell getShell() {
		return fWorkbenchPart.getSite().getShell();
	}

}
