package general;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import objects.Button;
import objects.Crate;
import objects.Human;
import objects.Templates;
import objects.Wall;

public class Level {
	public Templates[][] grid;
	public Human human;
	public Map<Integer,Button> inputs = new HashMap<Integer, Button>();

	public Level(String levelName) {
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(new File(levelName + ".png"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		grid = new Templates[bi.getWidth()][bi.getHeight()];
		for (int x = 0; x < bi.getWidth(); x++) {

			for (int y = 0; y < bi.getHeight(); y++) {
				int color = bi.getRGB(x, y);
				int r = (color >> 16) & 0xFF;
				int g = (color >> 8) & 0xFF;
				int b = (color >> 0) & 0xFF;
				if (Color.BLACK.getRGB() == bi.getRGB(x, y)) {
					grid[x][y] = new Wall();
				} else if (Color.GREEN.getRGB() == bi.getRGB(x, y)) {
					human = new Human(new Location(x, y));
					grid[x][y] = new Templates();
				} else if (Color.CYAN.getRGB() == bi.getRGB(x, y)) {
					grid[x][y] = new Crate();
				} else if (r == 187 && b == 0) {
					if (inputs.get(g) == null) {
						Button bs =new Button(new Location(x, y));
						bs.outputs = this.getInputs(levelName, g);
						inputs.put(g, bs);
					}
					grid[x][y] = new Templates();
				} else {
					grid[x][y] = new Templates();
				}
			}
		}
	}

	public ArrayList<Location> getInputs(String levelname, int gChan) {
		BufferedImage bi = null;
		ArrayList<Location> input = new ArrayList<Location>();
		try {
			bi = ImageIO.read(new File(levelname + "_electricity.png"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int x = 0; x < bi.getWidth(); x++) {

			for (int y = 0; y < bi.getHeight(); y++) {
				int color = bi.getRGB(x, y);
				int r = (color >> 16) & 0xFF;
				int g = (color >> 8) & 0xFF;
				int b = (color >> 0) & 0xFF;
				if (r == 187 && g == gChan && b == 1) {
					input.add(new Location(x, y));
				}
			}
		}
		return input;
	}

	public void move(int i, int j) {

		Location temp = human.location.translate(i, j);
		if (!(grid[temp.x][temp.y] instanceof Wall)
				&& !(grid[temp.x][temp.y] instanceof Crate)) {
			human.location = temp;
		} else if (grid[temp.x][temp.y].state == "moveable") {
			Location temp2 = temp.translate(i, j);
			if (grid[temp2.x][temp2.y].state != "moveable"
					&& grid[temp2.x][temp2.y].state != "solid") {
				grid[temp2.x][temp2.y] = grid[temp.x][temp.y];
				grid[temp.x][temp.y] = new Templates();
				human.location = temp;
			} else {
			}
			
		}
		
	}
}