/******************************************************************************
 * Copyright (c) 2006, Intalio Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Intalio Inc. - initial API and implementation
 *******************************************************************************/

package org.eclipse.stp.bpmn.diagram.edit.parts;

import java.util.Iterator;
import java.util.List;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateConnectionRequest;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateUnspecifiedTypeConnectionRequest;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel;
import org.eclipse.gmf.runtime.emf.type.core.MetamodelType;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.stp.bpmn.Activity;
import org.eclipse.stp.bpmn.ActivityType;
import org.eclipse.stp.bpmn.BpmnPackage;
import org.eclipse.stp.bpmn.diagram.edit.policies.Activity2CanonicalEditPolicy;
import org.eclipse.stp.bpmn.diagram.edit.policies.Activity2GraphicalNodeEditPolicy;
import org.eclipse.stp.bpmn.diagram.edit.policies.Activity2ItemSemanticEditPolicy;
import org.eclipse.stp.bpmn.diagram.part.BpmnVisualIDRegistry;
import org.eclipse.stp.bpmn.diagram.providers.BpmnElementTypes;
import org.eclipse.stp.bpmn.figures.activities.ActivityNodeFigure;
import org.eclipse.stp.bpmn.policies.ConnectionHandleEditPolicyEx;
import org.eclipse.stp.bpmn.policies.GenericEAnnotationDropPolicy;
import org.eclipse.stp.bpmn.policies.ResizableActivityEditPolicy;
import org.eclipse.stp.bpmn.tools.EdgeConnectionValidator;

/**
 * @generated
 */
public class Activity2EditPart extends ShapeNodeEditPart {
    /**
     * @notgenerated
     */
    private static final int EVENT_FIGURE_SIZE = 30;

    /**
     * @generated
     */
    public static final int VISUAL_ID = 2003;

    /**
     * @generated
     */
    protected IFigure contentPane;

    /**
     * @generated
     */
    protected IFigure primaryShape;

    /**
     * @generated
     */
    public Activity2EditPart(View view) {
        super(view);
    }

    /**
     * @generated
     */
    protected void createDefaultEditPoliciesGen() {
        super.createDefaultEditPolicies();
        installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
                new Activity2ItemSemanticEditPolicy());
        installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE,
                new Activity2GraphicalNodeEditPolicy());
        installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
                new Activity2CanonicalEditPolicy());
        installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
    }
    /**
     * @notgenerated
     */
    protected void createDefaultEditPolicies() {
        createDefaultEditPoliciesGen();
//      replace ConnectionHandleEditPolicy with our own
        removeEditPolicy(EditPolicyRoles.CONNECTION_HANDLES_ROLE);
        installEditPolicy(EditPolicyRoles.CONNECTION_HANDLES_ROLE,
				new ConnectionHandleEditPolicyEx());
     // adding default drag and drop edit policy
        installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, 
        		new GenericEAnnotationDropPolicy(this));
    }

    /**
     * @generated
     */
    protected LayoutEditPolicy createLayoutEditPolicy() {
        LayoutEditPolicy lep = new LayoutEditPolicy() {

            protected EditPolicy createChildEditPolicy(EditPart child) {
                EditPolicy result = child
                        .getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
                if (result == null) {
                    result = new NonResizableEditPolicy();
                }
                return result;
            }

            protected Command getMoveChildrenCommand(Request request) {
                return null;
            }

            protected Command getCreateCommand(CreateRequest request) {
                return null;
            }
        };
        return lep;
    }

    /**
     * @generated
     */
    protected IFigure createNodeShapeGen() {
        ActivityFigure figure = new ActivityFigure();
        return primaryShape = figure;
    }

    /**
     * @notgenerated
     */
    protected IFigure createNodeShape() {
        ActivityFigure figure = (ActivityFigure) createNodeShapeGen();
        setActivityTypeAndLabel(figure, (Activity) getPrimaryView()
                .getElement());
        return figure;
    }

    /**
     * Sets the acivity type on the figure.
     * Computes the default label if no name is set on the domain model object.
     * The default label is empty for all activities except the Task.
     * @param activityFigure
     * @param activity
     * @return
     */
    private static boolean setActivityTypeAndLabel(
            ActivityFigure activityFigure, Activity activity) {
        activityFigure.setActivityType(activity.getActivityType().getLiteral());
        if (activity.getName() == null) {
            WrapLabel wl = activityFigure.getFigureActivityNameFigure();
            if (activity.getActivityType().getValue() == ActivityType.TASK) {
                if (!"Task".equals(wl.getText())) {
                    wl.setText("Task");
                    return true;
                }
            } else {
                if (!"".equals(wl.getText())) {
                    wl.setText("");
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @generated
     */
    public ActivityFigure getPrimaryShape() {
        return (ActivityFigure) primaryShape;
    }

    /**
     * @generated
     */
    protected boolean addFixedChild(EditPart childEditPart) {
        if (childEditPart instanceof ActivityName2EditPart) {
            ((ActivityName2EditPart) childEditPart).setLabel(getPrimaryShape()
                    .getFigureActivityNameFigure());
            return true;
        }
        return false;
    }

    /**
     * @generated
     */
    protected boolean removeFixedChild(EditPart childEditPart) {
        return false;
    }

    /**
     * @notgenerated
     */
    protected NodeFigure createNodePlate() {
        return new ActivityNodeFigure(getMapMode().DPtoLP(EVENT_FIGURE_SIZE),
                getMapMode().DPtoLP(EVENT_FIGURE_SIZE)) {
            @Override
            public void setBounds(Rectangle rect) {
                if (rect.width != EVENT_FIGURE_SIZE) {
                    rect.width = EVENT_FIGURE_SIZE;
                }
                if (rect.height != EVENT_FIGURE_SIZE) {
                    rect.height = EVENT_FIGURE_SIZE;
                }
                if (prefSize == null) {
                    prefSize = rect.getSize();
                } else {
                    rect.height = rect.width;
                }
                super.setBounds(rect);
            }
        };
    }

    /**
     * Creates figure for this edit part.
     * 
     * Body of this method does not depend on settings in generation model so
     * you may safely remove <i>generated</i> tag and modify it.
     * 
     * @generated
     */
    protected NodeFigure createNodeFigure() {
        NodeFigure figure = createNodePlate();
        figure.setLayoutManager(new StackLayout());
        IFigure shape = createNodeShape();
        figure.add(shape);
        contentPane = setupContentPane(shape);
        return figure;
    }

    /**
     * Default implementation treats passed figure as content pane. Respects
     * layout one may have set for generated figure.
     * 
     * @param nodeShape
     *            instance of generated figure class
     * @generated
     */
    protected IFigure setupContentPane(IFigure nodeShape) {
        if (nodeShape.getLayoutManager() == null) {
            ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
            layout.setSpacing(getMapMode().DPtoLP(5));
            nodeShape.setLayoutManager(layout);
        }
        return nodeShape; // use nodeShape itself as contentPane
    }

    /**
     * @generated
     */
    public IFigure getContentPane() {
        if (contentPane != null) {
            return contentPane;
        }
        return super.getContentPane();
    }

    /**
     * @generated
     */
    public EditPart getPrimaryChildEditPart() {
        return getChildBySemanticHint(BpmnVisualIDRegistry
                .getType(ActivityName2EditPart.VISUAL_ID));
    }

    /**
     * @notgenerated
     */
    @Override
    public EditPolicy getPrimaryDragEditPolicy() {
        return new ResizableActivityEditPolicy();
    }

    /**
     * @generated
     */
    protected void addChildVisual(EditPart childEditPart, int index) {
        if (addFixedChild(childEditPart)) {
            return;
        }
        super.addChildVisual(childEditPart, -1);
    }

    /**
     * @generated
     */
    protected void removeChildVisual(EditPart childEditPart) {
        if (removeFixedChild(childEditPart)) {
            return;
        }
        super.removeChildVisual(childEditPart);
    }

    /**
     * Synchronizes the shape with the activityType
     * 
     * @notgenerated
     * @see org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart#handlePropertyChangeEvent(java.beans.PropertyChangeEvent)
     */
    protected void handleNotificationEvent(Notification notification) {
        if (notification.getEventType() == Notification.SET
                && BpmnPackage.eINSTANCE.getActivity_ActivityType().equals(
                        notification.getFeature())) {
            getPrimaryShape().setActivityType(
                    ((ActivityType) notification.getNewValue()).getLiteral());
            // System.err.println("JUST SET ACTIVITY_TYPE_ONSUB_PROCESS'S
            // ACTIVITY");
            // refreshVisuals();
        }
        super.handleNotificationEvent(notification);
    }

    /**
     * @notgenerated
     */
    @Override
    public Command getCommand(Request _request) {
        if (_request instanceof CreateUnspecifiedTypeConnectionRequest) {
            Object model = ((CreateUnspecifiedTypeConnectionRequest) _request)
                    .getTargetEditPart().getModel();

            if ((model instanceof Node)) {
                List elTypes = ((CreateUnspecifiedTypeConnectionRequest) _request)
                        .getElementTypes();
                MetamodelType connType = (MetamodelType) BpmnElementTypes.MessagingEdge_3002;

                for (int i = 0; i < elTypes.size(); i++) {
                    if (elTypes.get(i) instanceof MetamodelType) {
                        connType = (MetamodelType) elTypes.get(i);
                        break;
                    }
                }

                if (connType == BpmnElementTypes.MessagingEdge_3002) {
                    return null;
                }

                if (connType == BpmnElementTypes.SequenceEdge_3001) {
                    // edge connection rules
                    EdgeConnectionValidator edgeValidator = new EdgeConnectionValidator();

                    if (_request instanceof CreateUnspecifiedTypeConnectionRequest) {
                        CreateUnspecifiedTypeConnectionRequest request = (CreateUnspecifiedTypeConnectionRequest) _request;

                        if (request.isDirectionReversed()) {
                            // do nothing
                        } else {
                            if ((request.getSourceEditPart() != null)
                                    && (request.getTargetEditPart() != null)) {
                                for (Iterator iter = request.getAllRequests()
                                        .iterator(); iter.hasNext();) {
                                    CreateConnectionRequest connectionRequest = (CreateConnectionRequest) iter
                                            .next();
                                    if (connectionRequest.getSourceEditPart() != null
                                            && connectionRequest
                                                    .getTargetEditPart() != null
                                            && connectionRequest
                                                    .getSourceEditPart() == request
                                                    .getSourceEditPart()
                                            && connectionRequest
                                                    .getTargetEditPart() == request
                                                    .getTargetEditPart()) {
                                        //request is not reversed
                                        if (!edgeValidator.canConnect(request
                                                .getSourceEditPart(), request
                                                .getTargetEditPart())) {
                                            return null;
                                        }
                                    }
                                }

                            }

                            if ((request.getSourceEditPart() == null)
                                    && (request.getTargetEditPart() != null)) {
                                if (!edgeValidator.canStart(request
                                        .getTargetEditPart())) {
                                    return null;
                                }
                            }
                        }
                    }
                }
            }
        }

        return super.getCommand(_request);
    }

    /**
     * @generated
     */
    public class ActivityFigure extends
            org.eclipse.stp.bpmn.figures.activities.ActivityFigure {

        /**
         * @notgenerated
         */
        public ActivityFigure() {
            super();
            this.setActivityType("Task");

            this.setForegroundColor(org.eclipse.draw2d.ColorConstants.black

            );

            createContents();
        }

        /**
         * @generated
         */
        private void createContents() {
            org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel fig_0 = new org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel();
            setFigureActivityNameFigure(fig_0);

            Object layData0 = null;

            this.add(fig_0, layData0);
        }

        /**
         * @generated
         */
        private org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel fActivityNameFigure;

        /**
         * @generated
         */
        public org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel getFigureActivityNameFigure() {
            return fActivityNameFigure;
        }

        /**
         * @generated
         */
        private void setFigureActivityNameFigure(
                org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel fig) {
            fActivityNameFigure = fig;
        }

        /**
         * @generated
         */
        private boolean myUseLocalCoordinates = false;

        /**
         * @generated
         */
        protected boolean useLocalCoordinates() {
            return myUseLocalCoordinates;
        }

        /**
         * @generated
         */
        protected void setUseLocalCoordinates(boolean useLocalCoordinates) {
            myUseLocalCoordinates = useLocalCoordinates;
        }

    }
}
