/*
 * PressPad.cpp
 *
 *  Created on: 2009-07-12
 *      Author: wasyl
 */

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

#include "PressPad.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"

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

	mWorld = NULL;
	mOn = mLast = false;
}

PressPad::~PressPad()
{
}

Rect PressPad::bbox()
{
	return Rect(mPos.x, mPos.y + 14, mPos.x + 20, mPos.y + 20);
}

void PressPad::update(double dt)
{
	mOn = false;
	Entities &ents = mWorld->index(ID("prss"));
	FOREACH(vector,Entity*,e,ents)
	{
		Vec point = (*e)->pos() + Vec(10, 19);
		if (bbox().contains(point))
			mOn = true;
		point = (*e)->pos() + Vec(15, 19);
		if (bbox().contains(point))
			mOn = true;
		point = (*e)->pos() + Vec(5, 19);
		if (bbox().contains(point))
			mOn = true;
	}

	bool tileSetting = (mOn && (!mDefault)) || ( (!mOn) && mDefault );
	// propagate change
	Tile::setPresent(mControls, tileSetting);

	if (mLast != mOn)
		al_play_sample(mSndSwitch, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
	mLast = mOn;
}

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

void PressPad::load(FILE *f)
{
	Entity::load(f);
	mControls = loadByte(f);
	mDefault = loadByte(f);
}

void PressPad::save(FILE *f)
{
	Entity::save(f);
	saveByte(f, mControls);
	saveByte(f, mDefault);
}
