package dk.itu.mario.level.grammar;

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

import dk.itu.mario.level.LevelComponent;

public class LevelParseTree {
	private ParseNode root;
	private int start;
	private int width;
	
	public LevelParseTree(ParseNode root, int start, int width) {
		this.root = root;
		this.start = start;
		this.width = width;
	}
	
	public List<LevelComponent> getLevelTemplate() {
		List<LevelComponent> levelCompList = new ArrayList<LevelComponent>();
		getComponents(root,start,width, levelCompList);
		return levelCompList;
	}
	
	/**
	 * Enumerate the leaf nodes (level components) in depth-first order.
	 * @param node
	 * @param start
	 * @param end
	 */
	private void getComponents(ParseNode node, int start, int end, List<LevelComponent> levelCompList) {
		int numChildren = node.getNumChildren();
		if (numChildren == 0) {
			LevelComponent.TYPE lcType = node.getType();
			levelCompList.add(new LevelComponent(lcType, start, end));
		} else {
			int width = end - start;
			int childOffset = 0;
			for (int childIndex = 0; childIndex < numChildren; childIndex++) {
				ParseNode childNode = node.getChild(childIndex);
				int childStart = start + childOffset;
				int childWidth = (int)(width * childNode.getPercentLength());
				if (childIndex > 0) {
					getComponents(childNode,childStart+1,childStart + childWidth,levelCompList);
				} else { // don't offset by 1 if this is the first child component.
					getComponents(childNode,childStart,childStart + childWidth,levelCompList);
				}
				childOffset += childWidth;
			}
		}
	}
}