#include <string.h>
#include "drawable.h"
#include "malloc.h"

DrawableImage::DrawableImage() : Image()
{
	// Empty!
}

void DrawableImage::createImage(int width, int height)
{
	// Call on the image's create class
	_InitializeImage(width, height);
}

void DrawableImage::copyBuffer(u8 *buf)
{
	// Dont draw if we don't have a surface
	if(!_pixels) { return; }
	
	// This function assumes the u8 buffer is RGBA quads
	u8 *pixBuf = _pixels;
	
	u32 tWidth = GetWidth();
	u32 tHeight = GetHeight();
	
	// Loop in chunks of 4
	for(u32 j = 0; j < tHeight; j += 4)
	{
		for(u32 i = 0; i < tWidth; i += 4) 
		{
			// First, copy AR chunks
			for(u32 y = 0; y < 4; y++)
			{
				for(u32 x = 0; x < 4; x++)
				{
					// Alpha
					pixBuf[0] = buf[(((i + x) + ((j + y) * tWidth)) * 4) + 3];
					
					// Red
					pixBuf[1] = buf[((i + x) + ((j + y) * tWidth)) * 4];
					
					// Move pointer
					pixBuf+=2;
				}
			}
			
			// Now, copy GB chunks
			for(u32 y = 0; y < 4; y++)
			{
				for(u32 x = 0; x < 4; x++)
				{
					// Green
					pixBuf[0] = buf[(((i + x) + ((j + y) * tWidth)) * 4) + 1];
					
					// Blue
					pixBuf[1] = buf[(((i + x) + ((j + y) * tWidth)) * 4) + 2];
					
					// Move pointer
					pixBuf+=2;
				}
			}
		}
	}
	
	// Move flush cached memory
	_Flush();
}

Image *DrawableImage::getImage()
{
	return (Image *)this;
}
