#include "Python.h"

#include "maya/MStatus.h"
#include "maya/MLibrary.h"
#include "maya/MGlobal.h"


// global init
static bool _mayaInitialized = false;


static PyObject* maya_initialize(PyObject* self, PyObject* args)
{
	if (!_mayaInitialized)
	{
		// initialize Maya
		// script output to stdout
		// view-only license
		MStatus status = MLibrary::initialize(true, "mayamodule", true);
		if (status != MS::kSuccess)
		{
			printf("// Error: Failed to initialize Maya, exiting...\n");
			exit(1);
		}
		
		// remember
		_mayaInitialized = true;
	}
	else
		printf("// Warning: Maya already initialized\n");

	Py_INCREF(Py_None);
	return Py_None;
}


static PyObject* maya_mel(PyObject* self, PyObject* args)
{
	const char* command;
	if (PyArg_ParseTuple(args, "s", &command))
	{
		printf("Executing '%s'...\n", command);
		MStringArray results;
		MStatus status = MGlobal::executeCommand(MString(command), results);
		if (status != MS::kSuccess)
			printf("// Error: %s\n", status.errorString().asChar());
		else
			for (unsigned int i = 0; i < results.length(); i++)
				printf("// %s\n", results[i].asChar());
	}

	Py_INCREF(Py_None);
	return Py_None;
}


static PyObject* maya_cleanup(PyObject* self, PyObject* args)
{
	// shut down Maya
	if (_mayaInitialized)
	{
		printf("// Shutting down Maya");
		MLibrary::cleanup();
	}

	// this will never be reached since MLibrary::cleanup() does an exit()
	Py_INCREF(Py_None);
	return Py_None;
}


static PyMethodDef maya_methods[] =
{
	{"initialize",	maya_initialize,	METH_NOARGS,	"Initialize Maya library"},
	{"mel",			maya_mel,			METH_VARARGS,	"Execute arbitrary MEL command"},
	{"cleanup",		maya_cleanup,		METH_NOARGS,	"Shut down Maya library and exit"},
	{NULL, NULL}
};


PyMODINIT_FUNC
initmaya()
{
	printf("// mayamodule v1.0\n");

	Py_InitModule("maya", maya_methods);
}
