#include "BstmSprite.h"

namespace Brainstem
{
	Sprite::Sprite(IDirect3DDevice9* device)
	{
		Device = device;

		SetTechnique("Default");
		SetDefaultProperties();
	}

	Sprite::~Sprite() { }

	bool Sprite::Init()
	{
		D3DXCreateSprite(Device, &SpriteBatch);

		Filter = Color(1.0f, 1.0f, 1.0f, 1.0f);

		FrameCount = 0.0f;
		AnimationSpeed = 1.0f;
		PauseTime = 40.0f;
		CurrentFrame = 0;
		IsPaused = false;

		return true;
	}

	void Sprite::Update()
	{
		FrameCount += AnimationSpeed;

		if (FrameCount >= Textures.size())
		{
			IsPaused = true;
			FrameCount = 0;
			return;
		}

		CurrentFrame = (int)FrameCount;
	}

	void Sprite::Render(ICamera* camera)
	{
		if (Textures.size() <= 0)
			return;

		Texture* textureData = (Texture*)((ITexture*)Textures[CurrentFrame]);

		if (textureData == NULL)
		{
			WRITE_ERROR(this, "No Texture for Frame " << CurrentFrame);
			return;
		}


		SpriteBatch->Begin(D3DXSPRITE_ALPHABLEND);

		D3DXMATRIX Matrix;

		D3DSURFACE_DESC Surface;
		textureData->Data->GetLevelDesc(0, &Surface);
		Center = Vector2<float>(Position.X, Position.Y);

		D3DXMatrixTransformation2D(&Matrix, 
			&D3DXVECTOR2(Center.X, Center.Y), 
			0.0f, 
			&D3DXVECTOR2(Scale.X, Scale.Y), 
			&D3DXVECTOR2(Center.X, Center.Y), 
			Rotation.X,
			&D3DXVECTOR2(Position.X, Position.Y));

		SpriteBatch->SetTransform(&Matrix);
		SpriteBatch->Draw(textureData->Data, NULL, &D3DXVECTOR3(Center.X, Center.Y, 0.0f), NULL, D3DXCOLOR(Filter.R, Filter.G, Filter.B, Filter.A));

		SpriteBatch->End();
	}

	void Sprite::Release()
	{
		WRITE_RELEASE(this);
		SAFE_RELEASE(SpriteBatch)
	}

	void Sprite::ApplyTexture(ITexture* texture)
	{
		Textures.push_back(texture);
	}
	
	ITexture* Sprite::GetTexture()
	{
		return NULL;
	}
}