/******************************************************************************
 * 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
 *******************************************************************************/

/**
 * Date             Author              Changes
 * Dec 5, 2006     MPeleshchsyhyn         Created
 **/
package org.eclipse.stp.bpmn.commands;

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

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
import org.eclipse.gmf.runtime.diagram.ui.commands.CreateViewAndOptionallyElementCommand;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.stp.bpmn.diagram.edit.parts.BpmnDiagramEditPart;
import org.eclipse.stp.bpmn.diagram.edit.parts.PoolEditPart;

/**
 * Overrides CreateViewAndOptionallyElementCommand to support pool's specifics
 * 
 * @author MPeleshchyshyn
 * @author <a href="http://www.intalio.com">&copy; Intalio, Inc.</a>
 */
public class CreateViewAndOptionallyElementCommandEx extends
        CreateViewAndOptionallyElementCommand {

    public CreateViewAndOptionallyElementCommandEx(IAdaptable elementAdapter,
            IGraphicalEditPart containerEP, Point location,
            PreferencesHint preferencesHint) {
        super(elementAdapter, containerEP, location, preferencesHint);
    }

    @Override
    protected View getExistingView(EObject element) {
        IGraphicalEditPart container = getContainerEP();
        while (!(container instanceof BpmnDiagramEditPart)) {
            container = (IGraphicalEditPart) container.getParent();
        }

        List pools = container.getChildren();

        for (Iterator iter = pools.iterator(); iter.hasNext();) {
            IGraphicalEditPart gep = (IGraphicalEditPart) iter.next();
            if (!(gep instanceof PoolEditPart)) {
                continue;
            }
            IGraphicalEditPart theTarget = (IGraphicalEditPart) gep
                    .findEditPart(null, element);

            if (theTarget != null) {
                return (View) theTarget.getModel();
            }
        }

        return null;
    }

}
