package net.woodyfolsom.msproj.ann;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.woodyfolsom.msproj.GameRecord;
import net.woodyfolsom.msproj.Referee;

import org.antlr.runtime.RecognitionException;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataPair;
import org.junit.Test;

public class WinFilterTest {

	@Test
	public void testLearnSaveLoad() throws IOException, RecognitionException {
		File[] sgfFiles = new File("data/games/random_vs_random")
				.listFiles(new FileFilter() {
					@Override
					public boolean accept(File pathname) {
						return pathname.getName().endsWith(".sgf");
					}
				});

		Set<List<MLDataPair>> trainingData = new HashSet<List<MLDataPair>>();

		for (File file : sgfFiles) {
			FileInputStream fis = new FileInputStream(file);
			GameRecord gameRecord = Referee.replay(fis);

			List<MLDataPair> gameData = new ArrayList<MLDataPair>();
			for (int i = 0; i <= gameRecord.getNumTurns(); i++) {
				gameData.add(new GameStateMLDataPair(gameRecord.getGameState(i)));
			}

			trainingData.add(gameData);

			fis.close();
		}

		WinFilter winFilter = new WinFilter();

		winFilter.learn(trainingData);

		for (List<MLDataPair> trainingSequence : trainingData) {
			for (int stateIndex = 0; stateIndex < trainingSequence.size(); stateIndex++) {
				if (stateIndex > 0 && stateIndex < trainingSequence.size()-1) {
					continue;
				}
				MLData input = trainingSequence.get(stateIndex).getInput();
				
				System.out.println("Turn " + stateIndex + ": " + input + " => "
						+ winFilter.compute(input));
			}
		}
	}
}
