/*
 * Garbage.cpp
 *
 *  Created on: 2009-07-11
 *      Author: wasyl
 */

#include <cmath>
#include <allegro5/a5_primitives.h>

#include "Garbage.h"
#include "../prep/res/Resources.h"
#include "../misc/Controls.h"
#include "../prep/misc/Vector2D.h"
#include "../misc/Physics.h"
#include "../prep/misc/Random.h"
#include "Level.h"
#include "Game.h"
#include "Particle.h"

Garbage::Garbage()
{
	Resources::load(mSprite, "media/loosesheet.png");
	Resources::load(mSndCollect, "media/pickup.wav");

	mFrame = randomInt(0,2);
	mWorld = NULL;
	mTime = 0.0;
}

Garbage::~Garbage()
{
}

void Garbage::update(double dt)
{
	mTime += dt;

	Entity *avatar = mWorld->entity(ID("avat"));
	if (avatar->bbox().contains(mPos + Vec(10,10)))
	{
		al_play_sample(mSndCollect, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);

		discard();
		Game::get()->count(Game::GARBAGE, 1);
		for (int i = 0; i < 30; i++)
		{
			float dir = randomFloat(0.0,6.28);
			float pow = randomFloat(25.0, 45.0);
			Particle *p = new Particle(
					"media/glow.png",
					mPos + Vec(randomFloat(-5.0, 5.0), randomFloat(-5.0, 5.0)),
					Vec(std::sin(dir) * pow, std::cos(dir) * pow), 0.4, -0.02, ALLEGRO_ONE);
			mWorld->add(p);
		}
	}
}

void Garbage::render()
{
	float y = mPos.y + std::sin(mTime * 5.0) * 2.0;
	al_draw_bitmap(mSprite->get(mFrame), mPos.x, y, 0);

	float frac = mTime - int(mTime);
	if (frac < 0.4)
	{
		al_set_blender(ALLEGRO_ALPHA, ALLEGRO_ONE, al_map_rgba(255,255,255,128 - frac * 319));
		/*al_draw_filled_rectangle(
				mPos.x + 10.0 - frac * 25.0,
				mPos.y + 10.0 - frac * 25.0,
				mPos.x + 10.0 + frac * 25.0,
				mPos.y + 10.0 + frac * 25.0,
				al_map_rgb(255,255,255));*/
		al_draw_filled_ellipse(mPos.x + 10.0, mPos.y + 10, frac * 25.0, frac * 25.0, al_map_rgb(255,255,255));

		al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba(255,255,255,255));
	}
}
