package net.woodyfolsom.msproj;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class SGFWriter {

	public static void write(OutputStream os, GameRecord gameRecord)
			throws IOException {
		OutputStreamWriter writer = new OutputStreamWriter(os);

		writer.write("(");

		writer.write(";FF[4]GM[1]");

		GameConfig gameConfig = gameRecord.getGameConfig();

		writer.write("SZ[" + gameConfig.getSize() + "]");
		writer.write("KM[" + gameConfig.getKomi() + "]");

		for (int i = 1; i <= gameRecord.getNumTurns(); i++) {
			Player player = gameRecord.getPlayerToMove(i-1);
			if (Player.BLACK == player) {
				writer.write(";B[");
			} else if (Player.WHITE == player) {
				writer.write(";W[");
			} else {
				throw new RuntimeException("Invalid player: " + player);
			}
			Action action = gameRecord.getMove(i);
			String sgfCoord;
			if (action.isPass()) {
				sgfCoord = "";
			} else {
				sgfCoord = action.toSGF(gameConfig.getSize());
			}
			writer.write(sgfCoord + "]");
		}

		writer.write(")");
		writer.flush();
	}
}