#include "VexImageHandler.h"
#include "FreeImage.h"

int VexImageHandler::sSpinLock = 500;

VexImageHandler::VexImageHandler()
{
	// Clear the bindings
	mImageBindings.clear();

	// Initialize FreeImage
	FreeImage_Initialise();

	// Set the reference counter
	mRefCounter = 0;
}



VexImageHandler::~VexImageHandler()
{
	// Delete all the images in memory
	std::map<UT_String, VexImage*>::iterator iter;
	for(iter = mImageBindings.begin(); iter != mImageBindings.end(); ++iter)
	{
		VexImage* img = iter->second;
		delete img;
		img = NULL;
	}

	// De-initialize the free image lib
	FreeImage_DeInitialise();
}



// Clears all the images and resets the image array
void VexImageHandler::ClearImages()
{
	// Delete all the images in memory
	std::map<UT_String, VexImage*>::iterator iter;
	for(iter = mImageBindings.begin(); iter != mImageBindings.end(); ++iter)
	{
		VexImage* img = iter->second;
		delete img;
		img = NULL;
	}

	mImageBindings.clear();
}



// Create or fetch the image requested
VexImage* VexImageHandler::GetImage(const UT_String& inImageName)
{
	mSpinLock.lock(sSpinLock);

	// Try to find the image in our map
	VexImage* image = FindImage(inImageName);
	if(image == NULL)
	{
		// Otherwise create it
		image = new VexImage(inImageName);
		mImageBindings[inImageName] = image;
	}

	mSpinLock.unlock();

	// Return it
	return image;
}



// Finds an image in the binding, return NULL if not found
VexImage* VexImageHandler::FindImage(const UT_String& inImageName)
{
	if(mImageBindings.size() == 0)
		return NULL;

	if(!mImageBindings.count(inImageName))
		return NULL;

	return mImageBindings[inImageName];
}