/*
 * Level.cpp
 *
 *  Created on: 2009-07-10
 *      Author: wasyl
 */

#include "Level.h"
#include "../prep/ent/World.h"
#include "../prep/Common.h"
#include <vector>

Level::Level()
{
	for (int x = 0; x < 40; x++)
		for (int y = 0; y < 30; y++)
			tiles[x][y] = NULL;
}

Level::~Level()
{
	for (int x = 0; x < 40; x++)
		for (int y = 0; y < 30; y++)
			if (tiles[x][y])
				delete tiles[x][y];
}

Tile *Level::tile(int x, int y)
{
	if ((x < 0) || (x >= 40) || (y < 0) || (y >= 30))
		return NULL;
	return tiles[x][y];
}

void Level::setup()
{
	for (int x = 0; x < 40; x++)
		for (int y = 0; y < 30; y++)
			if (tiles[x][y])
			{
				tiles[x][y]->setLevel(this, x, y);
				tiles[x][y]->setup();
			}
}

void Level::addTiles(World *world)
{
	Entities &ts = world->index(ID("tile"));
	FOREACH(vector,Entity*,t,ts)
	{
		int x = int((*t)->x()) / 20;
		int y = int((*t)->y()) / 20;
		tiles[x][y] = (Tile*)(*t);
	}

	Entities &loose = world->index(ID("loos"));
	mGarbageCount = loose.size();

	setup();
}

Tile* Level::collision(Vec pos)
{
	int x = (int)(pos.x) / 20;
	int y = (int)(pos.y) / 20;
	Tile *t = tile(x,y);
	if (t && t->present())
		return t;
	else
		return NULL;
}
