#include "ScriptSystem_Image.h"

#include "TextureImage.h"

namespace BlueCore
{

//------------------------------------------------------------------------------
static weak_ptr<TextureManager> gTextureManager;
static weak_ptr<RenderDevice> gRenderDevice;

//------------------------------------------------------------------------------
static SQInteger _image_releasehook(SQUserPointer p, SQInteger size)
{
	TextureImage *image = (TextureImage *)p;

	if (image)
		image->removeReference();

	return 1;
}

//------------------------------------------------------------------------------
static SQInteger _image_constructor(HSQUIRRELVM vm)
{
	SQInteger argc = sq_gettop (vm );

	if (argc < 6)
		return 0;

	TextureImage *image = 0;

	const SQChar *texturename = 0;
	SQFloat ax, ay, bx, by;

	sq_getstring(vm, 2, &texturename );
	sq_getfloat(vm, 3, &ax );
	sq_getfloat(vm, 4, &ay );
	sq_getfloat(vm, 5, &bx );
	sq_getfloat(vm, 6, &by );

	Texture *texture = gTextureManager->loadTexture(texturename, 0, 0);
	image = new TextureImage( gRenderDevice, texture, ax, ay, bx, by );
	image->addReference();
	
	sq_setinstanceup(vm, 1, (void *)image );
	sq_setreleasehook (vm, 1, _image_releasehook );

	return 0;
}

//------------------------------------------------------------------------------
static SQInteger _image_draw(HSQUIRRELVM vm)
{
	int argc = sq_gettop (vm );

	if (argc < 3)
		return 0;

	TextureImage *image = 0;
	sq_getinstanceup (vm, 1, ( void ** ) &image, 0);

	if (image )
	{
		SQFloat x, y, r = 0.0;
		SQInteger halign = 0, valign = 0;

		sq_getfloat (vm, 2, &x );
		sq_getfloat (vm, 3, &y );

		if (argc > 3)
		{
			sq_getinteger(vm, 4, &halign );
		}

		if (argc > 4)
		{
			sq_getinteger(vm, 5, &valign );
		}

		if (argc > 5)
		{
			sq_getfloat(vm, 6, &r );
		}

		image->draw(x, y, halign, valign, r );
	}

	return 0;
}

//------------------------------------------------------------------------------
void setupScriptSystem_Image(ScriptSystem* scriptsystem,
		TextureManager* texturemanager, RenderDevice* renderdevice)
{
	if (scriptsystem == 0|| texturemanager == 0|| renderdevice == 0)
		return;

	gTextureManager = texturemanager;
	gRenderDevice = renderdevice;
	
	HSQUIRRELVM vm = scriptsystem->getVM();
	
	sq_pushroottable (vm );

	// push class
	sq_pushstring (vm, "Image", -1);

	if (SQ_SUCCEEDED (sq_newclass (vm, SQFalse ) ) )
	{
		// register constructor
		sq_pushstring (vm, "constructor", -1);
		sq_newclosure (vm, _image_constructor, 0);
		sq_newslot (vm, -3, false);

		sq_pushstring (vm, "draw", -1);
		sq_newclosure (vm, _image_draw, 0);
		sq_newslot (vm, -3, false);

		// create class
		sq_newslot (vm, -3, false);
	}

	sq_poptop (vm );
}
}
