package main.maps;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import main.DoorTile;
import main.Tile;

public class ImageMap extends Map {

	// Erstellung der abzulesenden Tiles (einem Tile wird eine farbe zugewiesen)

	private static PixelTile[] pixels = { new PixelTile(Tile.STONE_WALL, new Color(100, 100, 100)),
			new PixelTile(Tile.STONE_FLOOR, new Color(127, 127, 127)), new PixelTile(Tile.VOID, new Color(0, 0, 0)),
			new PixelTile(Tile.DOOR_LEFT_TOP, new Color(255, 150, 0)),
			new PixelTile(Tile.DOOR_LEFT_BOTTOM, new Color(69, 150, 0)),
			new PixelTile(Tile.STONE_WALL_BOTTOM, new Color(145, 145, 145)),
			new PixelTile(Tile.STONE_FLOOR_SHADOW_LEFT, new Color(251, 251, 129)) };

	public ImageMap(String path) {
		super(15, 11);

		try {
			BufferedImage img = ImageIO.read(ImageMap.class.getResourceAsStream(path));
			if (img.getWidth() != 15 || img.getHeight() != 11) {
				System.err.println("Odd map size! Use 15x11");
			}
			for (int x = 0; x < img.getWidth(); x++) {
				for (int y = 0; y < img.getHeight(); y++) {
					int id = Tile.VOID;
					int rgb = img.getRGB(x, y);
					for (PixelTile t : pixels) {
						if (t.c == rgb) {
							id = t.id;
							break;
						}
					}
					if (id == Tile.DOOR_LEFT_BOTTOM) {
						DoorTile door = new DoorTile(id, x, y, this);
						leftDoor = door;
						door.setSide(DoorTile.LEFT);
						tiles[x][y] = door;
						add(tiles[x][y]);
						continue;
					}
					
					tiles[x][y] = new Tile(id, x, y);
					add(tiles[x][y]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ImageMap(ImageMap map) {
		super(map.getWidth(), map.getHeight());
		cloneTiles(map);
	}

	private static class PixelTile {
		public final int c;
		public final int id;

		public PixelTile(int id, Color c) {
			this.c = c.getRGB();
			this.id = id;
		}
	}

	@Override
	public ImageMap clone() {
		return new ImageMap(this);
	}
}
