#include <malloc.h>
#include "image.h"

LoadableImage::LoadableImage() : Widget()
{
	// Set default state
	imageSprite = NULL;
	imageImage = NULL;
	
	// No path
	curImage = NULL;
	
	// Regular image
	_div = 1;
	_cur = 0;
}

LoadableImage::~LoadableImage()
{
	// Free images
	if(imageSprite) 
	{ 
		delete imageSprite; 
	}
	if(imageImage) 
	{ 
		imageImage->DestroyImage();
		delete imageImage; 
	}
	
	imageSprite = NULL;
	imageImage = NULL;
	
	// free caption
	if(curImage) { free(curImage); }
	curImage = NULL;
}

bool LoadableImage::setImage(const char *url)
{
	// Kill old images
	if(imageSprite) { delete imageSprite; }
	if(imageImage) { delete imageImage; }
	imageSprite = NULL;
	imageImage = NULL;
	
	if(url != curImage)
	{
		// Kill old storage
		if(curImage) { free(curImage); }
		
		// Allocate storage
		curImage = (char *)malloc(strlen(url) + 1);
		
		// Copy
		memcpy(curImage, url, strlen(url) + 1);
	}
	
	// Create new image
	imageImage = new Image();
	imageSprite = new Sprite();
	
	// Figure out pathname
	char pathName[MAXPATHLEN];
	windowManager.getThemePath(pathName);
	
	strcpy(pathName, pathName);
	strcat(pathName, url);
	
	if(imageImage->LoadImage(pathName) != IMG_LOAD_ERROR_NONE)
	{		
		// No default for images
		delete imageImage;
		delete imageSprite;
		
		imageSprite = NULL;
		imageImage = NULL;
		
		return false;
	}
	
	// Remember width and height
	_rect.width = imageImage->GetWidth();
	_rect.height = imageImage->GetHeight();
	
	// Success
	return true;
}

void LoadableImage::resize(int width, int height)
{
	// We dont resize images
	return;
}

void LoadableImage::setTransparency(int t)
{
	// Limit
	if(t < 0) { t = 0; }
	if(t > 255) { t = 255; }
	
	// Don't do anything if sprite doesn't exist
	if(!imageSprite) { return; }
	
	// Set transparency in libwiisprite
	imageSprite->SetTransparency(t);
}

void LoadableImage::draw()
{
	// Grab location including parent
	Rect dLoc = getDimensions();
	
	// Ensure its been loaded
	if(!imageSprite)
	{
		// It hasn't
		return;
	}
	
	// Create a window
	LayerManager manager(1);
	
	if(_div < 2)
	{
		// Set sprite up
		imageSprite->SetImage(imageImage);
	}
	else
	{
		// Set sprite up with divisions
		imageSprite->SetImage(imageImage, imageImage->GetWidth() / _div, imageImage->GetHeight());
		
		// Set which division
		imageSprite->SetFrame(_cur);
	}
	
	// Ensure label appears in the proper place
	imageSprite->SetPosition(dLoc.x, dLoc.y);
	
	// Append label to window
	manager.Append(imageSprite);
	
	// Draw to screen
	manager.Draw(settingsManager.getOffsetX(), settingsManager.getOffsetY());
}

void LoadableImage::setDivisions(int x)
{
	// Limit
	if(x < 1) { x = 1; }
	
	// Remember divisions
	_div = x;
	
	// Remember width and height
	if(imageImage)
	{
		_rect.width = imageImage->GetWidth() / _div;
		_rect.height = imageImage->GetHeight();
	}
}

void LoadableImage::selectDivision(int x)
{
	// Limit
	if(x < 0) { x = 0; }
	if(x >= _div) { x = _div - 1; }
	
	// Remember which state
	_cur = x;
}
