package chess4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.ParseException;

import groovy.lang.MissingMethodException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import chess4j.attack.Attack;
import chess4j.board.Board;
import chess4j.eval.Evaluator;
import chess4j.exceptions.IllegalMoveException;
import chess4j.io.InputParser;
import chess4j.moves.MoveGen;
import chess4j.search.Search;
import chess4j.utils.TestSuite;

public final class App {

	// These are all interfaces.  See the applicationContext for the implementation.
	private static Attack _attack;
	private static Board _board;
	private static Evaluator _eval;
	private static MoveGen _movegen;
	private static Search _search;

	private App() { }
	
	public static Attack getAttack() {
		return _attack;
	}

	public static Board getBoard() {
		return _board;
	}

	public static Evaluator getEval() {
		return _eval;
	}

	public static MoveGen getMoveGen() {
		return _movegen;
	}
	
	public static Search getSearch() {
		return _search;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		_attack = (Attack)ctx.getBean("attack");
		_board = (Board)ctx.getBean("board");
		_eval = (Evaluator)ctx.getBean("evaluator");
		_movegen = (MoveGen)ctx.getBean("movegen");
		_search = (Search)ctx.getBean("search");

		
		System.out.println("Welcome to chess4j!!\n\n");
		
		
		// process command line arguments
		for (String arg : args) {
			if (arg.startsWith("-ts=")) {
				String suite = arg.substring(4);
				TestSuite.process(new File(suite));
				System.exit(0);
			}
		}
		
		BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
		String input = "";
		while (true) {
			input = bin.readLine();
			try {
				InputParser.getInstance().parseCommand(input);
			} catch (IllegalMoveException ime) {
				System.out.println("Illegal move");
			} catch (ParseException pe) {
				System.out.println("Illegal move");
			} catch (MissingMethodException me) {
				System.out.println("Error (unknown command): " + input);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
