package map;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;

import main.Window;
import physics.*;

import physics.DeltaTimer;

public class Map implements Drawable {
	private ArrayList<MapItem> items = new ArrayList<>();
	private CollisionHandler ch = new CollisionHandler();

	public final DeltaTimer dt;

	private ArrayList<Integer> removalQueue = new ArrayList<>();

	public Map(DeltaTimer t) {
		this.dt = t;
	}

	public void addItem(MapItem item) {
		items.add(item);
	}

	public boolean removeItem(MapItem item) {
		for (int i = 0; i < items.size(); i++) {
			if (items.get(i) == item) {
				removalQueue.add(i);
				return true;
			}
		}
		return false;
	}

	private void doRemoval() {
		if (!removalQueue.isEmpty()) {
			Collections.sort(removalQueue);
			System.out.println("Calling do removal");
			for (int idx = removalQueue.size() - 1; idx >= 0; idx--) {
				items.remove((int)removalQueue.get(idx));
			}
			removalQueue = new ArrayList<>();
		}
	}
	
	public void makeRing() {
		int s = Wall.SIZE.intX();
		int w = Window.GAME_WIDTH;
		int h = Window.GAME_HEIGHT;
		
		for (int r = 0; r < w; r += s*4) {
			for (int c = 0; c < h; c += s*4) {
				addItem(new Wall(new Vector(r, 0)));
				addItem(new Wall(new Vector(r, h - s)));
				addItem(new Wall(new Vector(0, c)));
				addItem(new Wall(new Vector(w - s, c)));
			}
		}
	}

	public void draw(Graphics2D g) {
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, Window.GAME_WIDTH, Window.GAME_HEIGHT);

		for (MapItem item : items) {
			item.draw(g);
		}
	}

	public void update() {
		for (int i = 0; i < items.size(); i++) {
			MapItem item = items.get(i);
			if (item instanceof Updatable) {
				((Updatable) item).update();
			}
		}

		for (int i = 0; i < items.size(); i++) {
			for (int j = i + 1; j < items.size(); j++) {
				// call collision handler
				if (ch.overlapping(items.get(i), items.get(j)))
					items.get(i).hit(items.get(j), this);
			}
		}
		doRemoval();
	}
}

@@ -387,15 +387,15 @@
 ist%3C
-Integer
+MapItem
 %3E re
@@ -673,16 +673,27 @@
 ue.add(i
+tems.get(i)
 );%0A%09%09%09%09r
@@ -798,43 +798,8 @@
 ) %7B%0A
-%09%09%09Collections.sort(removalQueue);%0A
 %09%09%09S
@@ -851,17 +851,19 @@
 or (
-int idx =
+MapItem m :
  rem
@@ -875,40 +875,72 @@
 ueue
-.size() - 1; idx %3E= 0; idx--) %7B%0A
+) %7B%0A%09%09%09%09int indexOf = items.indexOf(m);%0A%09%09%09%09if (indexOf != -1)%0A%09
 %09%09%09%09
@@ -956,34 +956,15 @@
 ove(
-(
 in
-t)removalQueue.get(idx)
+dexOf
 );%0A%09
@@ -1011,18 +1011,17 @@
 %0A%09%09%7D%0A%09%7D%0A
-%09
 %0A
+
 %09public 
@@ -1125,18 +1125,16 @@
 HEIGHT;%0A
-%09%09
 %0A%09%09for (
@@ -1153,25 +1153,27 @@
  %3C w; r += s
-*
+ * 
 4) %7B%0A%09%09%09for 
@@ -1197,17 +1197,19 @@
 ; c += s
-*
+ * 
 4) %7B%0A%09%09%09

fix index bound error