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

#include "Container.h"

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

#include "../prep/Common.h"
#include "Container.h"
#include "../prep/res/Resources.h"
#include "../misc/Controls.h"
#include "../prep/misc/Vector2D.h"
#include "../misc/Physics.h"
#include "../thing/Bag.h"
#include "../prep/misc/Random.h"
#include "Level.h"
#include "Game.h"
#include "Particle.h"
#include <vector>

Container::Container(Vec pos, int required)
	: mRequired(required)
{
	mPos = pos;
	Resources::load(mSprite, "media/contsheet.png");
	Resources::load(mFont, "media/font.ttf");
	Resources::load(mSndClang, "media/cont.wav");
}

Container::~Container()
{
}

Rect Container::bbox()
{
	return Rect(mPos.x + 2.0, mPos.y, mPos.x + 37.0, mPos.y + 10.0);
}

void Container::update(double dt)
{
	if (!mRequired)
		return;

	Entities &garbage = mWorld->index(ID("grbg"));
	FOREACH(vector,Entity*,g,garbage)
	{
		Bag *grb = (Bag*)(*g);
		Vec pos = grb->pos() + Vec(10,15);
		if (grb->state() == Carryable::FALLING && bbox().contains(pos))
		{
			grb->discard();
			mRequired--;
			al_play_sample(mSndClang, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);

			for (int i = 0; i < 40; i++)
			{
				Particle *p = new Particle(
					"media/glow.png",
					mPos + Vec(randomFloat(5.0, 35.0), randomFloat(-5.0, 10.0)),
					Vec(0.0,randomFloat(-37.0, -75.0)), 0.8, -0.02, ALLEGRO_ONE);
				mWorld->add(p);
			}
		}
	}
}

void Container::load(FILE *f)
{
	Entity::load(f);
	mRequired = loadByte(f);
}

void Container::save(FILE *f)
{
	Entity::save(f);
	saveByte(f, mRequired);
}

void Container::render()
{
	int frame = mRequired ? 0 : 1;
	al_draw_bitmap(mSprite->get(frame), mPos.x, mPos.y - 8.0, 0);

	if (!mRequired)
		return;

	al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgb(0,0,0));
	al_draw_textf(mFont, mPos.x + 21.0, mPos.y + 5.0, ALLEGRO_ALIGN_CENTRE, "%d", mRequired);
	al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgb(255,255,0));
	al_draw_textf(mFont, mPos.x + 20.0, mPos.y + 4.0, ALLEGRO_ALIGN_CENTRE, "%d", mRequired);
	al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgb(255,255,255));
}
