#include "ScriptSystem_Camera.h"
#include "ScriptSystem_Math.h"

#include "Camera.h"

namespace BlueCore
{

static SQInteger _camera_releasehook(SQUserPointer p, SQInteger size)
{
	Camera *camera = (Camera *)p;

	if (camera)
		camera->removeReference();

	return 1;
}

static SQInteger _camera_constructor(HSQUIRRELVM vm)
{
	SQInteger argc = sq_gettop(vm);

	if (argc < 1)
		return 0;

	Camera *camera = new Camera();
	camera->addReference();

	sq_setinstanceup(vm, 1, (void *)camera );
	sq_setreleasehook(vm, 1, _camera_releasehook);

	return 0;
}

static SQInteger _camera_setposition(HSQUIRRELVM v)
{
	Camera *camera = 0;

	sq_getinstanceup(v, 1, ( void ** ) &camera, 0);

	if (camera)
	{
		Vector3 position;
		int argc = sq_gettop(v);

		if (argc == 2)
		{
			_getvectorvalues(v, 2, position.x, position.y, position.z);
		}
		else if (argc == 4)
		{
			sq_getfloat(v, 2, &position.x);
			sq_getfloat(v, 3, &position.y);
			sq_getfloat(v, 4, &position.z);
		}

		camera->setPosition(position);
	}

	return 0;
}

static SQInteger _camera_lookat(HSQUIRRELVM v)
{
	Camera *camera = 0;

	sq_getinstanceup(v, 1, ( void ** ) &camera, 0);

	if (camera)
	{
		Vector3 position;
		int argc = sq_gettop(v);

		if (argc == 2)
		{
			_getvectorvalues(v, 2, position.x, position.y, position.z);
		}
		else if (argc == 4)
		{
			sq_getfloat(v, 2, &position.x);
			sq_getfloat(v, 3, &position.y);
			sq_getfloat(v, 4, &position.z);
		}

		camera->lookAt(position);
	}

	return 0;
}

void setupScriptSystem_Camera(ScriptSystem* scriptsystem)
{
	if (scriptsystem == 0)
		return;

	HSQUIRRELVM vm = scriptsystem->getVM();

	sq_pushroottable(vm);

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

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

		sq_pushstring(vm, "setPosition", -1);
		sq_newclosure(vm, _camera_setposition, 0);
		sq_newslot(vm, -3, false);

		sq_pushstring(vm, "lookAt", -1);
		sq_newclosure(vm, _camera_lookat, 0);
		sq_newslot(vm, -3, false);

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

	sq_poptop(vm);
}

}
