package misc;

import java.util.ArrayList;
import java.util.List;

import de.ugoe.cs.autoquest.eventcore.guimodel.GUIModel;
import de.ugoe.cs.autoquest.eventcore.guimodel.IGUIElement;


public class AlignmentHelpers extends GUIModel {
	

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2593092958275693133L;

	/**
	 * <p>
	 * return a common denominator for the provided list of GUI elements, i.e. a
	 * GUI element, that is part of the parent GUI hiearchy of all GUI elements
	 * in the list. If there is no common denominator, the method returns null.
	 * </p>
	 */
	private static IGUIElement getCommonDenominator(List<IGUIElement> guiElements) {
		IGUIElement commonDenominator = null;

		if (guiElements.size() > 0) {
			List<IGUIElement> commonDenominatorPath = new ArrayList<IGUIElement>();

			// create a reference list using the first GUI element
			IGUIElement guiElement = guiElements.get(0);
			while (guiElement != null) {
				// We can use every type
				// if (guiElementMatchesConsideredTypes(guiElement)) {
				commonDenominatorPath.add(0, guiElement);
				// }
				guiElement = guiElement.getParent();
			}

			if (commonDenominatorPath.size() == 0) {
				return null;
			}

			// for each other GUI element, check the reference list for the
			// first element in the
			// path, that is not common to the current one, and delete it as
			// well as it subsequent
			// siblings
			List<IGUIElement> currentPath = new ArrayList<IGUIElement>();
			for (int i = 1; i < guiElements.size(); i++) {
				currentPath.clear();
				guiElement = guiElements.get(i);
				while (guiElement != null) {
					// if (guiElementMatchesConsideredTypes(guiElement)) {
				    currentPath.add(0, guiElement);
					// }
					guiElement = guiElement.getParent();
				}

				// determine the index of the first unequal path element
				int index = 0;
				while ((index < commonDenominatorPath.size())
						&& (index < currentPath.size())
						&& commonDenominatorPath.get(index).equals(
								currentPath.get(index))) {
					index++;
				}

				// remove all elements from the common denonimator path, that do
				// not match
				while (index < commonDenominatorPath.size()) {
					commonDenominatorPath.remove(index);
				}
			}

			if (commonDenominatorPath.size() > 0) {
				commonDenominator = commonDenominatorPath
						.get(commonDenominatorPath.size() - 1);
			}
		}
		return commonDenominator;
	}

	public static int distanceBetween(IGUIElement first, IGUIElement second) {

		int hopcount1 = 0;
		int hopcount2 = 0;
		List<IGUIElement> tmp = new ArrayList<IGUIElement>();
		tmp.add(first);
		tmp.add(second);
		IGUIElement commonDenominator = getCommonDenominator(tmp);
		
		while(!(first.equals(commonDenominator))) {
			first = first.getParent();
			hopcount1++;
		}
		
		while(!(second.equals(commonDenominator))) {
			second = second.getParent();
			hopcount2++;
		}

		return hopcount1 + hopcount2;
	}

}
