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

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

#include "Lever.h"
#include "../prep/Common.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 "Tile.h"
#include "Level.h"
#include "Game.h"

Lever::Lever(int controls, bool def)
	: mControls(controls)
{
	Resources::load(mSprite, "media/tilesheet.png");
	Resources::load(mSndSwitch, "media/switch.wav");

	mWorld = NULL;
	mToggler = NULL;
	mOn = def;
}

Lever::~Lever()
{
}

void Lever::update(double dt)
{
	Entity *avatar = mWorld->entity(ID("avat"));
	if (avatar->bbox().contains(mPos + Vec(10,10)))
	{
		if (!mToggler)
		{
			al_play_sample(mSndSwitch, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
			mOn = !mOn;
			mToggler = avatar;
		}
	}
	else
		if (mToggler == avatar)
			mToggler = NULL;

	Entities &bags = mWorld->index(ID("grbg"));
	FOREACH(vector,Entity*,b,bags)
	{
		if ((*b)->bbox().contains(mPos + Vec(10, 10)))
		{
			if (!mToggler)
			{
				al_play_sample(mSndSwitch, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
				mOn = !mOn;
				mToggler = (*b);
			}
		}
		else
			if (mToggler == (*b))
				mToggler = NULL;
	}

	// propagate change
	Tile::setPresent(mControls, mOn);
}

void Lever::render()
{
	int frame = mOn ? 8 : 7;
	al_draw_bitmap(mSprite->get(frame), mPos.x, mPos.y, 0);
}

void Lever::load(FILE *f)
{
	Entity::load(f);
	mControls = loadByte(f);
	mOn = loadByte(f);
}

void Lever::save(FILE *f)
{
	Entity::save(f);
	saveByte(f, mControls);
	saveByte(f, mOn);
}
