#include "ScriptSystem_Model.h"

namespace BlueCore
{

//------------------------------------------------------------------------------
static weak_ptr<ModelManager> gModelManager;

//------------------------------------------------------------------------------
static SQInteger _model_releasehook(SQUserPointer p, SQInteger size)
{
	Model *model = (Model *)p;

	if (model)
		model->removeReference();

	return 1;
}

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

	Model *model = 0;

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

		sq_getstring(vm, 2, &name);

		if (gModelManager.valid())
		{
			model = gModelManager->loadModel(name);
			if (model)
				model->addReference();
		}
	}

	sq_setinstanceup(vm, 1, (void *)model );
	sq_setreleasehook(vm, 1, _model_releasehook);

	return 0;
}

//------------------------------------------------------------------------------
void setupScriptSystem_Model(ScriptSystem* scriptsystem, ModelManager* modelmanager)
{
	if (scriptsystem && modelmanager)
	{
		HSQUIRRELVM vm = scriptsystem->getVM();

		gModelManager = modelmanager;

		sq_pushroottable(vm);

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

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

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

		sq_poptop(vm);
	}
}
}
