package net.woodyfolsom.msproj.sgf;

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

public class SGFNode {
	public enum TYPE {
		ROOT, MOVE_BLACK, MOVE_WHITE, EMPTY, COMMENT
	}

	private List<SGFProperty> properties = new ArrayList<SGFProperty>();
	private TYPE type = TYPE.EMPTY;

	public void addProperty(SGFProperty property) {
		if (properties.size() == 0) {
			SGFIdentifier sgfIdent = property.getIdentifier();
			if (sgfIdent == SGFIdentifier.MOVE_BLACK) {
				type = TYPE.MOVE_BLACK;
			} else if (sgfIdent == SGFIdentifier.MOVE_WHITE) {
				type = TYPE.MOVE_WHITE;
			} else if (sgfIdent == SGFIdentifier.COMMENT) {
				type = TYPE.COMMENT;
			} else {
				type = TYPE.ROOT;
			}
		}
		properties.add(property);
	}

	public int getPropertyCount() {
		return properties.size();
	}

	public TYPE getType() {
		return type;
	}

	public SGFValue<?> getFirstValue(SGFIdentifier identifier) {
		for (int i = 0; i < properties.size(); i++) {
			if (identifier == properties.get(i).getIdentifier()) {
				return properties.get(i).getValues().get(0);
			}
		}
		throw new RuntimeException(
				"SGFNode does not contain a property with identifier '"
						+ identifier + "'");
	}

	public String toSGF() {
		if (properties.size() == 0) {
			throw new RuntimeException("SGFNode contains no properties");
		}

		SGFProperty firstProp = properties.get(0);

		String sgfFormatString = ";" + firstProp.toSGF();

		for (int i = 1; i < properties.size(); i++) {
			sgfFormatString += properties.get(i).toSGF();
		}

		return sgfFormatString;
	}
	
	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(";");
		for (SGFProperty property : properties) {
			stringBuilder.append(property.toString());
		}
		return stringBuilder.toString();
	}
}
