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

#include "Physics.h"
#include "../thing/Game.h"

Collision Physics::collisions(Entity *e)
{
	Rect bbox = e->bbox();
	Level *lv = Game::get()->level();

	Collision c = {Collision::NONE, NULL, 1000.0};
	Tile *tile;

	if (tile = lv->collision(bbox.bottomCenter()))
	{
		double pen = bbox.bottom() - tile->y();
		if (pen > 1 && pen < c.penetr)
		{
			c.penetr = pen;
			c.dir = Collision::DOWN;
			c.tile = tile;
		}
	}

	if (tile = lv->collision(bbox.topCenter()))
	{
		double pen = tile->y() + 20.0 - bbox.top();
		if (pen > 1 && pen < c.penetr)
		{
			c.penetr = pen;
			c.dir = Collision::UP;
			c.tile = tile;
		}
	}

	if (tile = lv->collision(bbox.leftCenter()))
	{
		double pen = tile->x() + 20.0 - bbox.left();
		if (pen > 1 && pen < c.penetr)
		{
			c.penetr = pen;
			c.dir = Collision::LEFT;
			c.tile = tile;
		}
	}

	if (tile = lv->collision(bbox.rightCenter()))
	{
		double pen = bbox.right() - tile->x();
		if (pen > 1 && pen < c.penetr)
		{
			c.penetr = pen;
			c.dir = Collision::RIGHT;
			c.tile = tile;
		}
	}

	if (c.dir == Collision::NONE)
		c.penetr = 0.0;

	return c;
}

void Physics::eject(Entity *e, Collision col)
{
	switch(col.dir)
	{
	case Collision::LEFT: e->setX(e->x() + col.penetr); break;
	case Collision::RIGHT: e->setX(e->x() - col.penetr); break;
	case Collision::UP: e->setY(e->y() + col.penetr); break;
	case Collision::DOWN: e->setY(e->y() - col.penetr); break;
	default:
		break;
	}
}
