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

#include "Message.h"

#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 "Level.h"
#include "Game.h"
#include <vector>


Message::Message(std::string message)
{
	Resources::load(mSprite, "media/tilesheet.png");
	Resources::load(mFont, "media/font.ttf");

	mPop = NULL;
	mWorld = NULL;
	setMessage(message);
}

void Message::setMessage(std::string message)
{
	mMessage = message;
	if (mPop && mWorld)
	{
		mWorld->remove(mPop);
		mPop = NULL;
	}
	mPop = new PopUp();
	mPop->addLine(mMessage.c_str(), "");
}

Rect Message::bbox()
{
	return Rect(mPos.x - 5.0, mPos.y, mPos.x + 25.0, mPos.y + 20.0);
}

void Message::update(double dt)
{
	if (!mPop->world())
		mWorld->add(mPop);

	Entity *avatar = mWorld->entity(ID("avat"));
	mPop->setShown(bbox().contains(avatar->pos() + Vec(10,10)));
}

void Message::load(FILE *f)
{
	Entity::load(f);
	int b;
	std::string msg = "";
	while ( (b = loadByte(f)) != '$' )
		msg += (char)b;
	setMessage(msg);
}

void Message::save(FILE *f)
{
	Entity::save(f);
	for (unsigned int i = 0; i < mMessage.length(); i++)
		saveByte(f, mMessage.at(i));
	saveByte(f, '$');
}

void Message::render()
{
	int frame = 6;
	al_draw_bitmap(mSprite->get(frame), mPos.x, mPos.y, 0);
}
