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

#include "Bag.h"
#include "../prep/res/Resources.h"
#include "../misc/Controls.h"
#include "../prep/misc/Vector2D.h"
#include "../misc/Physics.h"
#include "Level.h"
#include "Game.h"

Bag::Bag()
{
	Resources::load(mBmp, "media/bag.png");
	mPos = Vec(400, 0);

	mState = STANDING;
}

Bag::~Bag()
{
}

Rect Bag::bbox()
{
	return Rect(mPos.x + 2.0, mPos.y + 4.0, mPos.x + 17.0, mPos.y + 20.0);
}

void Bag::update(double dt)
{
	// collisions
	Collision col = Physics::collisions(this);
	int retries = 0;
	while (col.dir != Collision::NONE && retries++ < 20)
	{
		if (mCarrier)
			mCarrier->dropCarried();

		switch (col.dir)
		{
		case Collision::LEFT:
		case Collision::RIGHT:
			// no walking into walls
			Physics::eject(this, col);
			mVel = Vec(0,0);
			break;

		case Collision::DOWN:
			// landed in a floor
			if (mState == FALLING && mVel.y >= 0.0)
			{
				mState = STANDING;
				al_play_sample(mSndLand, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
			}

			Physics::eject(this, col);
			break;

		case Collision::UP:
			Physics::eject(this, col);
			mVel = Vec(0,0);
			break;

		default:
			break;
		}

		col = Physics::collisions(this);
	}

	// no floor? toggle to falling down
	if (mState == STANDING)
	{
		Level *lv = Game::get()->level();
		if ( !lv->collision(mPos + Vec(10.0, 21.0)) &&
				!lv->collision(mPos + Vec(5.0, 21.0)) &&
				!lv->collision(mPos + Vec(15.0, 21.0)))
		{
			mVel = Vec(0.0,0.0);
			mState = FALLING;
		}
	}

	if (mState == FALLING)
	{
		mVel.y += dt * 600.0;
		if (mVel.y > 600.0)
			mVel.y = 600.0;
		mPos += mVel * dt;
	}
}

void Bag::render()
{
	al_draw_bitmap(mBmp, mPos.x, mPos.y, 0);
}
