package zero1hd.rhythmbullet.entity;

import com.badlogic.gdx.utils.Pool;

public class EntityFrame<T extends Entity> {
	private Pool<T> pool;
	private EntityManager ec;
	Class<T> ct;
	EntityFrame<T> ef;
	
	/**
	 * Manages the entities pooling.
	 * @param entityController
	 * @param classType
	 */
	public EntityFrame(EntityManager entityController, Class<T> classType) {
		this.ct = classType;
		ef = this;
		ec = entityController;
		pool = new Pool<T>() {
			@Override
			protected T newObject() {
				try {
					T entity = ct.newInstance();
					entity.setup(ec, ef);
					
					return entity;
				} catch (InstantiationException | IllegalAccessException e) {
					e.printStackTrace();
					return null;

				}
			}
		};
	}
	
	public T buildEntity() {
		T entity = pool.obtain();
		
		if (entity.enemy) {
			ec.activeEnemies.add(entity);
		} else {
			ec.activeAllies.add(entity);
		}
		return entity;
	}
	
	
	/**
	 * Free the entity if no longer used.
	 * @param entity to be freed.
	 */
	protected void recycleEntity(Entity entity) {
		if (entity.enemy) {
			ec.activeEnemies.removeValue(entity, true);
		} else {
			ec.activeAllies.removeValue(entity, true);
		}
		pool.free(ct.cast(entity));
	}
	
	@Override
	public String toString() {
		return ct.getSimpleName();
	}
}
