/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * 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:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.editors.layout.outline;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.RootEditPart;

public class OutLineTreeEditPartFactory implements EditPartFactory {

	private GraphicalViewer graphicalViewer = null;
	private Map layoutEditPartMap = null;
	
	public OutLineTreeEditPartFactory(GraphicalViewer viewer) {
		graphicalViewer = viewer;
		layoutEditPartMap = getLayoutEditPartList(viewer.getRootEditPart());
	}

	private Map getLayoutEditPartList(EditPart root) {
		HashMap map = new HashMap();
		if (!(root instanceof RootEditPart)) {
			map.put(root.getModel(), root);
		}
		List partList = root.getChildren();
		for (int i = 0; i < partList.size(); i++) {
			map.putAll(getLayoutEditPartList((EditPart) partList.get(i)));
		}
		return map;
	}
	
	private EditPart getLayoutEditPart(Object model) {
		EditPart part = (EditPart) layoutEditPartMap.get(model);
		if (part == null) {
			part = findLayoutEditPart(graphicalViewer.getRootEditPart(), model);
			layoutEditPartMap.put(model, part);
		}
		return part;
	}
	
	private EditPart findLayoutEditPart(EditPart root, Object model) {
		if (!(root instanceof RootEditPart)) {
			if (root.getModel() == model) {
				return root;
			}
		}		
		List partList = root.getChildren();
		for (int i = 0; i < partList.size(); i++) {
			EditPart part = findLayoutEditPart((EditPart) partList.get(i), model);
			if (part != null) {
				return part;
			}
		}
		return null;
	}
	
	public EditPart createEditPart(EditPart context, Object model) {
		OutLineTreeEditPart part = new OutLineTreeEditPart();
		part.setModel(model);
		EditPart layoutPart = getLayoutEditPart(model);
		part.setLayoutEditPart(layoutPart);
		return part;
	}
}
