#include "StdAfx.h"
#include "Bomb.h"

#include "Level.h"
#include "Block.h"
#include "OGLrendrer.h"
#include "Character.h"

Bomb::Bomb(unsigned char size_, int x_, int y_)
{
	size = size_;
	x = x_;
	y = y_;
	triggered = false;
	associatedLevel = NULL;
}

Bomb::~Bomb(void)
{
}

void 
Bomb::explode()
{
	if(triggered)
		return;

	triggered = true;
	associatedLevel->removeBomb();

	Level *lev = associatedLevel;
	triggerArea(x, y, size, lev);	
	destroyArea(x, y, size, lev);
}


void 
Bomb::draw(OGLrendrer *ogl)
{
	void(__stdcall* glMultiTexCoord2dARB)(GLenum, double,double)=(void(__stdcall*)(GLenum,double,double))ogl->getGlProcAddress("glMultiTexCoord2dARB");

	float x_ = x+0.5;
	float y_ = y+0.5;

	float stickerSize = 0.8;
	if(size == 1)
		stickerSize /= 3;
	if(size == 2)
	{
		stickerSize /= 3;
		stickerSize *= 2;
	}

	glBindTexture(GL_TEXTURE_2D, 3);

	//glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, );

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	//glMatrixMode(GL_MODELVIEW);
	//glPushMatrix();
	//glLoadIdentity();
	//glRotatef(orientation, 0, 0, 1);
	float dev = stickerSize/2;
	glBegin(GL_QUADS);
		glMultiTexCoord2dARB(GL_TEXTURE0_ARB,0.00,1.0); glVertex3f(x_-dev, y_-dev, 1.1);
		glMultiTexCoord2dARB(GL_TEXTURE0_ARB,0.00,0.0); glVertex3f(x_-dev, y_+dev, 1.1);
		glMultiTexCoord2dARB(GL_TEXTURE0_ARB,1.00,0.0); glVertex3f(x_+dev, y_+dev, 1.1);
		glMultiTexCoord2dARB(GL_TEXTURE0_ARB,1.00,1.0); glVertex3f(x_+dev, y_-dev, 1.1);
	glEnd();
	//glPopMatrix();

	glDisable(GL_BLEND);
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}

void 
Bomb::setLevel(Level *a)
{
	associatedLevel = a;
}

void 
Bomb::setNewCoords(int x_, int y_)
{
	x = x_;
	y = y_;
}

void 
triggerArea(int x_, int y_, int size, Level *lev)
{
	// Now trigger bombs in the radius
	int dev = 0;
	for(int yCur = y_-size ; yCur<=(y_+size) ; yCur++)
	{
		triggerRow(x_, yCur, dev, lev);
		dev++;
		if(yCur >= y_)
			dev -=2;
	}
}

void 
triggerRow(int x_, int y_, int dev, Level *lev)
{
	int xOrig = x_ - dev;
	
	for(int xCur = xOrig ; xCur<=(x_+dev) ; xCur++)
	{
		lev->triggerExplosive(xCur, y_);
	}
}

void 
destroyArea(int x_, int y_, int size, Level *lev)
{
	// Now to destroy the blocks
	int dev = 0;
	for(int yCur = y_-(size-1) ; yCur<=(y_+(size-1)) ; yCur++)
	{
		destroyRow(x_, yCur, dev, lev);
		dev++;
		if(yCur >= y_)
			dev -=2;
	}
}

void 
destroyRow(int x_, int y_, int dev, Level *lev)
{
	int xOrig = x_ - dev;
	
	for(int xCur = xOrig ; xCur<=(x_+dev) ; xCur++)
	{
		Block *a = lev->getBlock(xCur, y_);
		if(a)
		{
			Character *nChar = lev->getCharacter();
			if(nChar)
			{
				float xPos, yPos;
				nChar->getPosition(&xPos, &yPos);
				if((xPos >= xCur) && (xPos < xCur+1) && (yPos >= y_) && (yPos < y_+1))
				{
					// Player was blown up.
					nChar->exploded();
				}
			}
			lev->removeBlock(a);
			delete a;
		}

	}
}