package chess4j.search;

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

import chess4j.App;
import chess4j.Constants;
import chess4j.board.Board;
import chess4j.hash.TTable;
import chess4j.io.PrintGameResult;
import chess4j.io.PrintLine;
import chess4j.moves.Move;
import chess4j.utils.GameStatus;
import chess4j.utils.GameStatusChecker;

/**
 * SearchIterator
 * @author james
 *
 */
public class SearchIterator implements Runnable {

	private static final SearchIterator INSTANCE = new SearchIterator();
	private static int maxDepth = 3;
	private List<Move> lastPV = new ArrayList<Move>();
	private SearchStats lastSearchStats;
	
	private SearchIterator() {
		lastSearchStats = new SearchStats();
	}
	
	public static SearchIterator getInstance() {
		return INSTANCE;
	}
	
	public List<Move> getLastPV() {
		return Collections.unmodifiableList(lastPV);
	}
	
	public SearchStats getLastSearchStats() {
		return lastSearchStats;
	}
	
	private void iterate() {
		Search search = App.getSearch();
		Board board = App.getBoard().deepCopy();
		List<Move> pv = new ArrayList<Move>();
		
		TTable.getInstance().clear();
		SearchStats stats = new SearchStats();
		for (int i=1;i<=maxDepth;i++) {
			search.search(pv,-Constants.INFINITY, Constants.INFINITY, board, i,stats);
			assert(pv.size()>0);
			
			System.out.print(i+". ");
			PrintLine.printLine(pv);
		}
		
		assert(pv.size()>0);
		lastPV.clear();
		lastPV.addAll(pv);
		lastSearchStats = stats;
		
		Move m = pv.get(0);
		App.getBoard().applyMove(m);
		System.out.println("move " + m);
	
		// if end of game print result
		GameStatus gs = GameStatusChecker.getGameStatus(App.getBoard());
		if (gs != GameStatus.INPROGRESS) {
			PrintGameResult.printResult(gs);
		}
	}
	
	public void run() {
		iterate();
	}
}
