/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * Portions of this software are based upon public domain software
 * originally written at the National Center for Supercomputing Applications,
 * University of Illinois, Urbana-Champaign.
 */
package com.bonevich.eclipse.cvsgrapher.editors;

import com.bonevich.eclipse.cvsgrapher.model.*;

import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.GraphicalEditPart;

import java.util.Iterator;

/**
 * The layout manager for the CVS Graph Editor.  Basically it is a <code>FreeformLayout</code>
 * but with an initializing routine to layout the tree.  Also allows the layout to
 * be reset ("snap" back to original layout).
 * 
 * @author jbonevic
 */
public final class CvsGraphLayout extends FreeformLayout
{
	private final CvsGraphModel _model;
	private final CvsGraphEditPart _editPart;
	
	private static final int BEGIN_X = 10;
	private static final int BEGIN_Y = 10;
	private static final int OFFSET_X = 40;
	private static final int OFFSET_Y = 40;
	
	private volatile boolean _initialized = false;

	public CvsGraphLayout(CvsGraphEditPart editPart)
	{
		_editPart = editPart;
		_model = (CvsGraphModel) editPart.getModel();
	}

	/**
	 * Rules for layout of CVS graph:
	 * <ul>
	 *   <li>Rule 1: Root node must be branch node ("MAIN")</li>
	 *   <li>Rule 2: Any node may have at most one child version node</li>
	 *   <li>Rule 3: Any version node may have any number of child nodes (i.e. one version, n branches)</li>
	 * </ul>
	 */
	private void initializeLayout()
	{
		// Rule 1
		CvsGraphBranchModel root = _model.getRootBranch();
		traverseTree(root, BEGIN_X, BEGIN_Y);

		setInitialized(true);
	}
	
	private int traverseTree(ICvsGraphNodeModel entry, int x, int y)
	{
		ICvsGraphNodeEditPart part = (ICvsGraphNodeEditPart) getEditPartForModel(entry);
		CvsGraphNodeViewHelper view = part.getViewHelper();
		Point entryLocation = new Point(x, y);
		view.setLocation(entryLocation);
		
		Dimension size = part.getFigure().getPreferredSize(-1,-1);
		int width = size.width;
		int height = size. height;
		int nextY = y + height + OFFSET_Y;
		
		int nextX = x;
		int childNodesWidth = 0;
		
		// Rule 2 and 3
		Iterator children = entry.getChildNodes().iterator();
		while (children.hasNext())
		{
			ICvsGraphNodeModel child = (ICvsGraphNodeModel) children.next();
			childNodesWidth += traverseTree(child, nextX, nextY);
			if (children.hasNext())
			{
				childNodesWidth += OFFSET_X;
				nextX = x + childNodesWidth;
			}
		}

		int subTreeWidth = Math.max(childNodesWidth, width);
		int shiftX = (subTreeWidth - width) / 2;
		Point adjustedLocation = entryLocation.translate(shiftX, 0);
		view.setLocation(adjustedLocation);
			
		return subTreeWidth;
	}
	
	private GraphicalEditPart getEditPartForModel(ICvsGraphNodeModel model)
	{
		return (GraphicalEditPart) _editPart.getRoot().getViewer().getEditPartRegistry().get(model);
	}

	/**
	 * @see org.eclipse.draw2d.LayoutManager#layout(org.eclipse.draw2d.IFigure)
	 */
	public void layout(IFigure parent)
	{
		super.layout(parent);
		if (!isInitialized())
		{
			initializeLayout();
		}
	}
	
	public void reset()
	{
		initializeLayout();
	}

	private synchronized boolean isInitialized()
	{
		return _initialized;
	}

	private synchronized void setInitialized(boolean initialized)
	{
		_initialized = initialized;
	}

}
