package net.robertboehm.ld22;

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

public class Mapgrid {
	
	public static final int NORTH = 0,
							EAST = 1,
							SOUTH = 2,
							WEST = 3;
	
	private final Map<Integer, GameMap> maps = new HashMap<Integer, GameMap>();
	private final int[] grid;
	private final int spawnMapId;
	private final int spawnX;
	private final int spawnY;
	public final int width;
	public final int height;
	
	
	public Mapgrid(int width, int height, int spawnMapId, int spawnX, int spawnY) {
		this.width = width;
		this.height = height;
		this.grid = new int[width * height];
		this.spawnMapId = spawnMapId;
		this.spawnX = spawnX;
		this.spawnY = spawnY;
	}
	
	public void addMap(int id, GameMap map) {
		this.maps.put(id, map);
	}
	
	public void setGridId(int x, int y, int id) {
		this.grid[GameMap.getTileId(x, y, width)] = id;
	}
	
	public int getNeighborId(int id, int direction) {
		int gridId = -1;
		int x = -1;
		int y = -1;
		for(int i = 0; i < grid.length; i++) {
			if(id == grid[i]) {
				gridId = i;
			}
		}
		
		y = GameMap.getTileY(gridId, width);
		x = GameMap.getTileX(gridId, y, width);
		
		if(gridId == -1 || x == -1 || y == -1)
			return -1;
		
		int nX = x;
		int nY = y;
		
		switch(direction) {
		case NORTH: nY--; break;
		case EAST: nX++; break;
		case SOUTH: nY++; break;
		case WEST: nX--; break;
		}
		
		if(nY < 0 || nX < 0 || nY >= height || nX >= width)
			return -1;
		
		return grid[GameMap.getTileId(nX, nY, width)];
	}
	
	public GameMap getMapById(int id) {
		return maps.get(id);
	}
	
	public GameMap getSpawnMap() {
		return maps.get(spawnMapId);
	}

	public int getSpawnMapId() {
		return spawnMapId;
	}
	
	public int getSpawnX() {
		return spawnX;
	}
	
	public int getSpawnY() {
		return spawnY;
	}

	public void feed(MapProvider mapProvider) {
		for(int i = 0; i < grid.length; i++) {
			if(grid[i] != -1 && !maps.containsKey(grid[i])) {
				maps.put(grid[i], mapProvider.getMap(grid[i]));
			}
		}
	}
	
}
