package net.robertboehm.ld22;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TileProperties {
	
	Map<Point, Integer> tileProperties = new HashMap<Point, Integer>();
	
	private static final Pattern PROPERTY_PATTERN = Pattern.compile("^([0-9]+),([0-9]+)=([TRBLF]+)$", Pattern.CASE_INSENSITIVE);
	private static final int PROPERTY_GROUP_X = 1;
	private static final int PROPERTY_GROUP_Y = 2;
	private static final int PROPERTY_GROUP_COLLISIONMODE = 3;
	
	public TileProperties(Reader r) throws IOException {
		try(BufferedReader br = new BufferedReader(r)) {
			String line;
			String trimmedLine;
			Matcher m;
			while((line = br.readLine()) != null) {
				trimmedLine = line.trim();
				if(!trimmedLine.startsWith("#")) {
					m = PROPERTY_PATTERN.matcher(trimmedLine);
					if(m.matches()) {
						int x = Integer.valueOf(m.group(PROPERTY_GROUP_X));
						int y = Integer.valueOf(m.group(PROPERTY_GROUP_Y));
						String collisionModeString = m.group(PROPERTY_GROUP_COLLISIONMODE);
						int collisionMode = 0;
						if(collisionModeString.contains("T"))
							collisionMode |= Tile.COLLISION_TOP;
						if(collisionModeString.contains("R"))
							collisionMode |= Tile.COLLISION_RIGHT;
						if(collisionModeString.contains("B"))
							collisionMode |= Tile.COLLISION_BOTTOM;
						if(collisionModeString.contains("L"))
							collisionMode |= Tile.COLLISION_LEFT;
						if(collisionModeString.contains("F"))
							collisionMode |= Tile.COLLISION_FILL;
						tileProperties.put(new Point(x, y), collisionMode);
					}
				}
			}
		}
	}

	public int getCollisionMode(int x, int y) {
		Integer c = tileProperties.get(new Point(x, y));
		return c == null ? 0 : c;
	}

}
