#include "SDL.h"
#include "SDL_opengl.h"


#include "container.h"
#include "entity.h"
#include "random.h"

namespace PRJID {


Container::Container() {
}
Container::~Container() {
	clear();
}

void Container::clear() {
}

void Container::add(Entity *e,bool special) {
	entities.push_back(e);
}

void Container::tick(unsigned int ticks) {
	if (ticks==0) return;
	std::list <Entity *>::iterator it;
	std::list <std::list <Entity *>::iterator>::iterator dit;
	std::list <std::list <Entity *>::iterator> todelete;

	for (it=entities.begin();it!=entities.end();it++) {
		(*it)->tick(ticks);
		if ((*it)->remove) {
			delete (*it);
			todelete.push_back(it);
		}
	}

	for (dit=todelete.begin();dit!=todelete.end();dit++) {
		entities.erase((*dit));
	}

}

void Container::act(unsigned int ticks) {
	std::list <Entity *>::iterator it;

	for (it=entities.begin();it!=entities.end();it++) {
		if ((*it)->type==ET_PLAYER) continue;
		(*it)->act(ticks);
	}
}

void Container::draw() {
	std::list <Entity *>::iterator it;

	for (it=entities.begin();it!=entities.end();it++) {
		if ((*it)==NULL) continue;
		if ((*it)->type==ET_PLAYER) continue;
		(*it)->draw();
	}
}

bool Container::collision_with_plane(C3f p,float rad) {
	std::list <Entity *>::iterator it;

	for (it=entities.begin();it!=entities.end();it++) {
		if ((*it)==NULL) continue;
		if ((*it)->type!=ET_PLANE2&&(*it)->type!=ET_PLANE1) continue;
		if ((*it)->get_position().too_far(p,rad)) continue;
		if (!(*it)->get_position().dist_below(p,rad*rad)) continue;

		(*it)->explode();
		return true;
	}
	return false;
}

void Container::set_game(Game *g) {
	game=g;
}


Entity * Container::create(e_entitytype t) {
	Entity *n;
	n=new Entity();
	n->set_game(game);
	n->set_container(this);
	n->set_type(t);
	add(n,true);
	return n;
}


} //namespace
