package com.imnotjames.tribbleengine.engine;

import com.imnotjames.tribbleengine.Family;
import com.imnotjames.tribbleengine.entity.Entity;

import java.util.ArrayList;
import java.util.List;

public class Engine {
	private List<Entity> entities;

	private List<EngineSystem> engineSystems;

	private List<EngineEventListener> listeners;

	public Engine() {
		this.entities = new ArrayList<Entity>();
		this.engineSystems = new ArrayList<EngineSystem>();
		this.listeners = new ArrayList<EngineEventListener>();
	}

	public void update(long delta) {
		for (EngineSystem s : engineSystems) {
			s.update(delta);
		}
	}

	public void addEntity(Entity entity) {
		this.entities.add(entity);

		EngineEntityEvent event = new EngineEntityEvent(this, entity);

		for (EngineEventListener listener : this.listeners) {
			listener.entityAdded(event);
		}
	}

	public void removeEntity(Entity entity) {
		// If we don't remove the entity don't fire events
		if (! this.entities.remove(entity)) {
			return;
		}

		EngineEntityEvent event = new EngineEntityEvent(this, entity);

		for (EngineEventListener listener : this.listeners) {
			listener.entityRemoved(event);
		}
	}

	public List<Entity> getEntities() {
		return this.entities;
	}

	public List<Entity> getEntities(Family family) {
		List<Entity> filteredEntities = new ArrayList<Entity>();

		for (Entity entity : this.entities) {
			if (family.matches(entity)) {
				filteredEntities.add(entity);
			}
		}

		return filteredEntities;
	}

	public void removeAllEntities() {
		while (this.entities.size() > 0) {
			this.removeEntity(this.entities.get(0));
		}
	}

	public void addSystem(EngineSystem engineSystem) {
		this.engineSystems.add(engineSystem);

		engineSystem.setUp(this);

		// this.engineSystems.sort();
	}

	public void removeSystem(EngineSystem engineSystem) {
		if (this.engineSystems.remove(engineSystem)) {
			engineSystem.tearDown(this);
		}
	}

	public void addEventListener(EngineEventListener listener) {
		this.listeners.add(listener);
	}

	public void removeEventListener(EngineEventListener listener) {
		this.listeners.remove(listener);
	}
}

@@ -1153,32 +1153,157 @@
 event);%0A%09%09%7D%0A%09%7D%0A%0A
+%09public void removeAllEntities() %7B%0A%09%09while (this.entities.size() %3E 0) %7B%0A%09%09%09this.removeEntity(this.entities.get(0));%0A%09%09%7D%0A%09%7D%0A%0A%0A
 %09public List%3CEnt
@@ -1613,132 +1613,8 @@
 %09%7D%0A%0A
-%09public void removeAllEntities() %7B%0A%09%09while (this.entities.size() %3E 0) %7B%0A%09%09%09this.removeEntity(this.entities.get(0));%0A%09%09%7D%0A%09%7D%0A%0A
 %09pub

move Engine.removeAllEntities