#include "Sprite.h"

#include "SDL.h"
#include "Visualisation.h"

#include <math.h> //Replace with fixed

#define PI 3.14159265
#define DEGTORAD(deg) (deg * (PI / 180))

Sprite::Sprite(const SpriteID &id)
: m_ID(id), m_pFrames(0), m_numFrames(0), m_width(0), m_height(0)
{
}

Sprite::~Sprite()
{
	Shutdown();
}

void Sprite::InitFromFile(char* filename)
{

}

void Sprite::Draw(const unsigned int &x, const unsigned int &y, unsigned int frame)
{
	SDL_Rect dstRect;
	dstRect.x = x; dstRect.y = y;
	SDL_BlitSurface(&m_pFrames[frame], 0, Visualisation::getSingleton()->GetScreen(), &dstRect);
}

void Sprite::Shutdown()
{
	for(size_t i = 0; i < m_numFrames; i++)
		SDL_FreeSurface(&m_pFrames[i]);
}

void Sprite::WritePixel(SDL_Surface* pSurface, int x, int y, const ColourRGB &colour)
{
	Uint32 mapColour = SDL_MapRGB(pSurface->format, colour.r, colour.g, colour.b);
	switch (pSurface->format->BytesPerPixel)
	{
		case 1: // Assuming 8-bpp
			Uint8 *p8Buffer;
			p8Buffer = (Uint8 *)pSurface->pixels + y * pSurface->pitch + x;
			*p8Buffer = mapColour;
			break;

		case 2: // Probably 15-bpp or 16-bpp
			Uint16 *p16Buffer;
			p16Buffer = (Uint16 *)pSurface->pixels + y * (pSurface->pitch / 2) + x;
			*p16Buffer = mapColour;
			break;

		case 3: // Slow 24-bpp mode, usually not used
			Uint8 *p24Buffer;
			p24Buffer = (Uint8 *)pSurface->pixels + y * pSurface->pitch + x * 3;
			if(SDL_BYTEORDER == SDL_LIL_ENDIAN)
			{
				p24Buffer[0] = mapColour;
				p24Buffer[1] = mapColour >> 8;
				p24Buffer[2] = mapColour >> 16;
			} 
			else 
			{
				p24Buffer[2] = mapColour;
				p24Buffer[1] = mapColour >> 8;
				p24Buffer[0] = mapColour >> 16;
			}
			break;

		case 4: // Probably 32-bpp
			Uint32 *p32Buffer;
			p32Buffer = (Uint32 *)pSurface->pixels + y * (pSurface->pitch / 4) + x;
			*p32Buffer = mapColour;
			break;
	}
}
