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

#include "SceneGraph.h"

namespace BlueCore
{

static SQInteger _scenegraph_releasehook(SQUserPointer p, SQInteger size)
{
	SceneGraph *scenegraph = (SceneGraph *)p;

	if (scenegraph)
		scenegraph->removeReference();

	return 1;
}

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

	if (argc < 1)
		return 0;

	SceneGraph *scenegraph = new SceneGraph();
	scenegraph->addReference();

	sq_setinstanceup(vm, 1, (void *)scenegraph );
	sq_setreleasehook(vm, 1, _scenegraph_releasehook);

	return 0;
}

static SQInteger _set_camera(HSQUIRRELVM v)
{
	SceneGraph *scenegraph = 0;

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

	if (scenegraph)
	{
		Camera *camera;
		sq_getinstanceup (v, 2, ( void ** ) &camera, 0);
		scenegraph->setCamera(camera);
	}

	return 0;
}

static SQInteger _attach_node(HSQUIRRELVM v)
{
	SceneGraph *scenegraph = 0;

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

	if (scenegraph)
	{
		SceneNode *node;
		sq_getinstanceup (v, 2, ( void ** ) &node, 0);
		scenegraph->getRootNode()->attach(node);
	}

	return 0;
}

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

	HSQUIRRELVM vm = scriptsystem->getVM();

	sq_pushroottable(vm);

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

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

		sq_pushstring(vm, "setCamera", -1);
		sq_newclosure(vm, _set_camera, 0);
		sq_newslot(vm, -3, false);

		sq_pushstring(vm, "attachNode", -1);
		sq_newclosure(vm, _attach_node, 0);
		sq_newslot(vm, -3, false);

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

	sq_poptop(vm);
}

}
