#include "ScriptSystem_SceneNode.h"
#include "ScriptSystem_Math.h"

#include "SceneNode.h"

namespace BlueCore
{

static SQInteger _scenenode_releasehook(SQUserPointer p, SQInteger size)
{
	SceneNode *node = (SceneNode *)p;

	if (node)
		node->removeReference();

	return 1;
}

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

	SceneNode *node = 0;

	if (argc > 1)
	{
		const SQChar *name = 0;

		sq_getstring(vm, 2, &name);

		node = new SceneNode (name);
		if (node)
			node->addReference();
	}

	sq_setinstanceup(vm, 1, (void *)node );
	sq_setreleasehook(vm, 1, _scenenode_releasehook);

	return 0;
}

static SQInteger _set_model(HSQUIRRELVM v)
{
	SceneNode *node = 0;

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

	if (node)
	{
		Model *model;
		sq_getinstanceup(v, 2, ( void ** ) &model, 0);
		node->setModel(model);
	}

	return 0;
}

static SQInteger _set_position(HSQUIRRELVM v)
{
	SceneNode *node = 0;

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

	if (node)
	{
		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);
		}

		node->setRelativeTranslation(position);
	}

	return 0;
}

void setupScriptSystem_SceneNode(ScriptSystem* scriptsystem)
{
	if (scriptsystem)
	{
		HSQUIRRELVM vm = scriptsystem->getVM();

		sq_pushroottable(vm);

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

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

			sq_pushstring(vm, "setModel", -1);
			sq_newclosure(vm, _set_model, 0);
			sq_newslot(vm, -3, false);

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

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

		sq_poptop(vm);
	}
}
}
