package net.woodyfolsom.msproj;

import java.util.HashMap;
import java.util.Map;

public class Action {
	private static final Map<String, Action> actionMap = new HashMap<String,Action>();
	
	private char column = 'x';
	private int row = 0;
	
	private String move;
	
	public static final Action NONE = new Action("NONE", 'x', 0);
	public static final Action PASS = new Action("PASS", 'x', 0);
	public static final Action RESIGN = new Action("RESIGN", 'x', 0);
	
	private Action(String move, char column, int row) {
		this.move = move;
		this.column = column;
		this.row = row;
	}
	
	public static final Action getInstance(String move) {
		if (move.length() < 2) {
			return Action.NONE;
		}

		if ("NONE".equals(move)) {
			return Action.NONE;
		}
		
		if ("PASS".equals(move)) {
			return Action.PASS;
		}
		
		if ("RESIGN".equals(move)) {
			return Action.RESIGN;
		}
		
		if (actionMap.containsKey(move)) {
			return actionMap.get(move);
		}
		
		Action action = Action.NONE;
		
		try {
			char col = move.charAt(0);
			int row = Integer.valueOf(move.substring(1));
		
			action = new Action(move, col, row);
			actionMap.put(move, action);
		} catch (NumberFormatException nfe) {
				return Action.NONE;
		}
		
		return action;
	}
	
	public char getColumn() {
		return column;
	}
	
	public int getRow() {
		return row;
	}
	
	public boolean isNone() {
		return this == Action.NONE;
	}
	
	public boolean isPass() {
		return this == Action.PASS;
	}
	
	public boolean isResign() {
		return this == Action.RESIGN;
	}
	
	public static Action parseSGF(String sgfCoord, int boardSize) {
		if (sgfCoord.length() == 0) {
			return Action.PASS;
		}
		StringBuilder sb = new StringBuilder();
		char column = sgfCoord.charAt(0);
		if (column >= 'i') {
			sb.append((char) (column + 1));
		} else {
			sb.append(column);
		}
		char row = sgfCoord.charAt(1);
		sb.append(boardSize - row + 'a');
		return Action.getInstance(sb.toString().toUpperCase());
	}
	
	public String toLatex(int boardSize) {
		if (isPass() || isNone() || isResign()) {
			throw new UnsupportedOperationException("Invalid Action for toLatex() call: " + this);
		}
		String latex = new String(new char[] {column}).toLowerCase();
		latex += row;
		return latex;
	}
	
	public String toSGF(int boardSize) {
		if (isNone() || isResign()) {
			throw new UnsupportedOperationException("Invalid Action for toLatex() call: " + this);
		}
		if (isPass()) {
			return ""; // or 'tt' in old format
		}
		char[] latex = new char[2];
		if (column >= 'J') {
			latex[0] = (char) (column - 1);
		} else {
			latex[0] = column;
		}
		latex[1] = (char)('a' + (boardSize - row));
		return new String(latex).toLowerCase();
	}
	
	@Override
	public String toString() {
		return move;
	}
}