#include "BallSprite.h"

#include "SDL.h"
#include "Visualisation.h"
#include <math.h>
#include "GameException.h"

#define PI 3.14159265f
#define DEGTORAD(deg) (deg * (PI / 180.0f))

BallSprite::BallSprite(const SpriteID &id, const int &radius, const ColourRGB &outerColour, const ColourRGB &centreColour)
: Sprite(id)
{
	m_width = m_height = radius * 2;

	m_numFrames = 1; //Only one frame for procedural balls so far, animation could be added later.
	SDL_Surface* pScreen = Visualisation::getSingleton()->GetScreen();
	m_pFrames = SDL_CreateRGBSurface(SDL_HWSURFACE, m_width, m_height, pScreen->format->BitsPerPixel, pScreen->format->Rmask, pScreen->format->Gmask, pScreen->format->Bmask, pScreen->format->Amask);

	if(!m_pFrames)
	{
		throw GameException(eMajorError, "BallSprite: Constructor failed due to failed SDL_CreateRGBSurface() call.");
		return;
	}


	if(SDL_MUSTLOCK(m_pFrames))
		SDL_LockSurface(m_pFrames);

	//Add clearing entire surface to transparent colour key here
	ColourRGB transColour = Visualisation::getSingleton()->GetTransparencyKey();
	Uint32 key = SDL_MapRGB(m_pFrames->format, transColour.r, transColour.g, transColour.b);
	SDL_SetColorKey(m_pFrames, SDL_SRCCOLORKEY, key);

	for(size_t x = 0; x < m_width; x++)
	{
		for (size_t y = 0; y < m_height; y++)
		{
			WritePixel(m_pFrames, x, y, transColour);
		}
	}

	ColourRGB colour;
	float fRad = (float)radius;

	for(int r = 0; r < radius; r++)
	{
		fRad = static_cast<float>(r);
		for(float i = 0; i < 360; i += 0.5f)
		{
			float degInRad = DEGTORAD(i);

			//Radius here is centre x and centre y
			int x = radius - (int)(cos(degInRad) * fRad);
			int y = radius - (int)(sin(degInRad) * fRad);

			float fLerpVal = fRad / (float)radius;
			colour.r = outerColour.r + (unsigned char)((float)(centreColour.r - outerColour.r) * fLerpVal);
			colour.g = outerColour.g + (unsigned char)((float)(centreColour.g - outerColour.g) * fLerpVal);
			colour.b = outerColour.b + (unsigned char)((float)(centreColour.b - outerColour.b) * fLerpVal);

			WritePixel(m_pFrames, x, y, colour);
		}
	}

	if(SDL_MUSTLOCK(m_pFrames))
		SDL_UnlockSurface(m_pFrames);
}
