package tetris.io;

import tetris.*;
import java.util.*;
import java.util.regex.*;

public class Factory {
	private Factory() {}
	
	private static Pattern pairPattern = Pattern.compile("\\((\\d+)\\,(\\d+)\\)");
	private static Pattern pieceBrackets = Pattern.compile("\\[([^\\]]*)\\]");
	private static Pattern offsetBrackets = Pattern.compile("\\{([^\\}]*)\\}");
	private static Pattern piecePattern = Pattern.compile("(" + pairPattern + ")(\\d)(" + offsetBrackets + ")");

	public static Well makeWell(String input) {
		String[] lines = input.split("\\|");
		Well result = new Well(lines[0].length(), lines.length);
		for (int i = 0, row = result.topRow(); i < lines.length; ++i, row += Well.downRow()) {
			String line = lines[i];
			for (int c = 0, col = result.leftSide(); c < line.length(); ++c, col += Well.rightCol()) {
				if (line.charAt(c) == 'O') {
					result.fill(row, col);
				}
			}
		}
		
		return result;
	}
	
	public static Piece makePiece(String input) {
		Matcher m = pieceBrackets.matcher(input);
		if (m.matches()) {
			System.out.println(m.group(1));
			Matcher pieceParts = piecePattern.matcher(m.group(1));
			System.out.println(pieceParts.matches() ? "matches" : "no match");
			for (int i = 1; i <= pieceParts.groupCount(); ++i) {
				System.out.println("group " + i + ": " + pieceParts.group(i));
			}
			Pair location = new Pair(Integer.parseInt(pieceParts.group(2)), Integer.parseInt(pieceParts.group(3)));
			int rotations = Integer.parseInt(pieceParts.group(4));
			
			ArrayList<Pair> offsets = new ArrayList<Pair>();
			String[] nums = pieceParts.group(6).split("[\\(|\\)|\\,]");
			for (int i = 0; i < nums.length; i+=3) {
				offsets.add(new Pair(Integer.parseInt(nums[i+1]), Integer.parseInt(nums[i+2])));
			}
			
			Piece result = new Piece(location, new PieceOffsets(offsets));
			for (int i = 0; i < rotations; ++i) {result.rotate();}
			return result;
		} else {
			throw new IllegalArgumentException("text '" +input+ "' is the wrong format");
		}
 	}
}
