package it.mice.voila2.helpers;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.ConfigureElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.internal.impl.AssociationImpl;

public class VoilaAssociationHelper extends AbstractEditHelperAdvice {
	@Override
	protected ICommand getAfterConfigureCommand(final ConfigureRequest request) {

		ICommand command = new ConfigureElementCommand(request) {

			@Override
			protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
				EObject elementToConfigure = request.getElementToConfigure();
				if (!(elementToConfigure instanceof AssociationImpl)) {
					return CommandResult.newErrorCommandResult("Element to configure was not a AssociationImpl: " + elementToConfigure);//$NON-NLS-1$
				}
				((AssociationImpl)elementToConfigure).getMemberEnds().get(0).setName(null);
				((AssociationImpl)elementToConfigure).getMemberEnds().get(1).setName(null);
				// retrieve stereotype 
				if (((AssociationImpl)elementToConfigure).getAppliedStereotypes().get(0).getName().equalsIgnoreCase("ManyToOneRelation")) {
					((AssociationImpl)elementToConfigure).getMemberEnds().get(0).setUpper(1);
					((AssociationImpl)elementToConfigure).getMemberEnds().get(0).setLower(0);					
					((AssociationImpl)elementToConfigure).getMemberEnds().get(1).setLower(0);
					((AssociationImpl)elementToConfigure).getMemberEnds().get(1).setUpper(-1);
				}
				else if (((AssociationImpl)elementToConfigure).getAppliedStereotypes().get(0).getName().equalsIgnoreCase("OneToOneRelation")) {			
					((AssociationImpl)elementToConfigure).getMemberEnds().get(1).setLower(0);
					((AssociationImpl)elementToConfigure).getMemberEnds().get(1).setUpper(1);
				}

				return CommandResult.newOKCommandResult(elementToConfigure);
			}
		};

		return command.compose(super.getAfterConfigureCommand(request));
	}
}

