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

#include "Tile.h"


#include <allegro5/allegro.h>
#include <allegro5/a5_primitives.h>
#include <allegro5/a5_opengl.h>

#include "../prep/res/Resources.h"
#include "../thing/Level.h"

/******************************************/

bool Tile::sTypePresent[10] = {1,1,1,1,1,1,1,1,1,1};

/******************************************/

Tile::Tile(int type, Level *level, int x, int y)
	: mType(type), mLevel(level), mX(x), mY(y)
{
	mPos = Vec(x*20.0,y*20.0);
	mBlack = al_map_rgb(0,0,0);
	mLight = al_map_rgba(255,255,255,64);
	mDark = al_map_rgba(0,0,0,64);
	mLines = 0;
	Resources::load(mSheet, "media/tilesheet.png");
}

bool Tile::differs(int x, int y)
{
	Tile *t = mLevel->tile(x,y);
	if (!t)
		return true;
	return (t->mType != mType);
}
void Tile::setup()
{
	mLines = 0;
	if (differs(mX-1,mY))
		mLines |= L;
	if (differs(mX+1,mY))
			mLines |= R;
	if (differs(mX,mY-1))
			mLines |= U;
	if (differs(mX,mY+1))
			mLines |= D;
}

void my_rect(float x1, float y1, float x2, float y2, float r, float g, float b, float a)
{
	glColor4f(r,g,b,a);
	glVertex2f(x1,y2);glVertex2f(x2,y2);
	glVertex2f(x2,y1);glVertex2f(x1,y1);
}

void Tile::render()
{
	if (present())
	{
		glDisable(GL_BLEND);
		al_draw_bitmap(mSheet->get(mType), mPos.x, mPos.y, 0);
		glEnable(GL_BLEND);

		glBegin(GL_QUADS);
		if (mLines & L)
			my_rect(mPos.x, mPos.y, mPos.x + 1, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 1.0f);
		if (mLines & R)
			my_rect(mPos.x + 19.0, mPos.y, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 1.0f);
		if (mLines & U)
		{
			my_rect(mPos.x, mPos.y, mPos.x + 20.0, mPos.y + 7.0, 1.0f, 1.0f, 1.0f, 0.25f);
			my_rect(mPos.x, mPos.y, mPos.x + 20.0, mPos.y + 1.0, 0.0f, 0.0f, 0.0f, 1.0f);
		}
		if (mLines & D)
		{
			my_rect(mPos.x, mPos.y+13.0, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 0.25f);
			my_rect(mPos.x, mPos.y+19.0, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 1.0f);
		}
		glEnd();
	}
	else
	{
		al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba(255,255,255,255));
		glBlendFunc(GL_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glBegin(GL_QUADS);
		if (mLines & L)
			my_rect(mPos.x, mPos.y, mPos.x + 1, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 0.5f);
		if (mLines & R)
			my_rect(mPos.x + 19.0, mPos.y, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 0.5f);
		if (mLines & U)
		{
			my_rect(mPos.x, mPos.y, mPos.x + 20.0, mPos.y + 7.0, 1.0f, 1.0f, 1.0f, 0.12f);
			my_rect(mPos.x, mPos.y, mPos.x + 20.0, mPos.y + 1.0, 0.0f, 0.0f, 0.0f, 0.5f);
		}
		if (mLines & D)
		{
			my_rect(mPos.x, mPos.y+13.0, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 0.12f);
			my_rect(mPos.x, mPos.y+19.0, mPos.x + 20.0, mPos.y + 20.0, 0.0f, 0.0f, 0.0f, 0.5f);
		}
		glEnd();
	}

}

void Tile::load(FILE *f)
{
	Entity::load(f);
	mType = loadByte(f);
}

void Tile::save(FILE *f)
{
	Entity::save(f);
	saveByte(f, mType);
}

