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

#include <allegro5/a5_primitives.h>
#include <allegro5/a5_font.h>
#include <allegro5/a5_ttf.h>

#include "GuiButton.h"
#include "../prep/res/Resources.h"
#include "../misc/Controls.h"
#include "../prep/app/AppState.h"

GuiButton::GuiButton(Rect r, std::string text, bool enabled)
	: mRect(r), mEnabled(enabled), mText(text)
{
	Resources::load(mFont, "media/font.ttf");
	Resources::load(mSndSelect, "media/land.wav");
	mClicked = false;
	mWorld = NULL;
}

GuiButton::~GuiButton()
{}

void GuiButton::update(double dt)
{
	if (!mEnabled)
	{
		setState(DISABLED);
		return;
	}

	ALLEGRO_MOUSE_STATE *ms = AppStateBase::current()->mouseState();

	if (mRect.contains(Vec(ms->x, ms->y)))
	{
		setState(HIGHLIGHTED);
		if (Controls::get().click->on())
		{
			mClicked = true;
			al_play_sample(mSndSelect, 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
		}
	}
	else
		setState(NORMAL);
}

void GuiButton::render()
{
	int alpha;
	switch (mState)
	{
	case DISABLED: alpha = 64; break;
	case NORMAL: alpha = 192; break;
	case HIGHLIGHTED: alpha = 255; break;
	}

	al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba(255,255,255,alpha));
	al_draw_filled_rectangle(mRect.left(), mRect.top(), mRect.right(), mRect.bottom(), al_map_rgb(48,48,64));
	al_draw_rectangle(mRect.left(), mRect.top(), mRect.right(), mRect.bottom(), al_map_rgb(0,0,0), 2.0);
	al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba(255,255,255,255));

	al_draw_text(mFont, mRect.topCenter().x, mRect.leftCenter().y - 7.0, ALLEGRO_ALIGN_CENTRE, mText.c_str());
}
