/**
 * PyVertexVisitor.cpp --
 *
 *	This file contains the vertex-visitor defintion.
 *
 *	Authors: Mike Krimerman.
 *		 hemkond@yahoo.com
 *
 * Copyright (c) 2003, Mike Krimerman.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE, EVEN IF
 * MIKE KRIMERMAN IS MADE AWARE OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "e4py.h"
#include <new>

/** Helpers */

/** PyVertexVisitor_New.
 * A helper function for object creation from C.
 */
PyObject* PyVertexVisitor_New()
{
	PyVertexVisitor* result = PyObject_NEW(PyVertexVisitor, &PyVertexVisitorType);
	if (result)
		new(&result->visitor) e4_VertexVisitor();		//Placement new
	return (PyObject*)result;
}

/** PyVertexVisitor_FromVertexVisitor.
 * A helper function for object creation from C.
 */
PyObject* PyVertexVisitor_FromVertexVisitor(e4_VertexVisitor visitor)
{
	PyVertexVisitor* result = PyObject_NEW(PyVertexVisitor, &PyVertexVisitorType);
	if (result)
		new(&result->visitor) e4_VertexVisitor(visitor);		//Placement new
	return (PyObject*)result;
}

/** PyVertexVisitor_AsVertexVisitor.
 *
 */
e4_VertexVisitor& PyVertexVisitor_AsVertexVisitor(PyObject* self)
{
	return ((PyVertexVisitor*)self)->visitor;
}

/** Methods */

/** PyVertexVisitor_Set.
 *
 */
static PyObject* PyVertexVisitor_Set(PyVertexVisitor* self, PyObject* args)
{
	bool success = false;
	switch (PyTuple_Size(args)) {
	case 1: {
		PyObject *obj;
		if (!PyArg_ParseTuple(args, "O", &obj))
			return 0;
		
		if (PyStorage_Check(obj)) {
			success = self->visitor.SetStorage(PyStorage_AsStorage(obj));
		} else if (PyNode_Check(obj)) {
			success = self->visitor.SetNode(PyNode_AsNode(obj));
		} else if (PyVertex_Check(obj)) {
			success = self->visitor.SetVertex(PyVertex_AsVertex(obj));
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	}
	case 2: {
		PyObject *obj;
		int dc;
		if (!PyArg_ParseTuple(args, "O!i", &PyStorageType, &obj, &dc))
			return 0;
		success = self->visitor.SetStorage(PyStorage_AsStorage(obj), e4_DetachChoice(dc));
		break;
	}
	case 3:
		if (PyStorage_Check(PyTuple_GetItem(args, 0))) {
			PyStorage *py_storage;
			const char *name;
			int vt;
			if (!PyArg_ParseTuple(args, "Osi", &py_storage, &name, &vt))
				return 0;
			success = self->visitor.SetStorage(py_storage->storage, name, e4_VertexType(vt));
		} else if (PyNode_Check(PyTuple_GetItem(args, 0))) {
			PyNode *py_node;
			const char *name;
			int vt;
			if (!PyArg_ParseTuple(args, "Osi", &py_node, &name, &vt))
				return 0;
			success = self->visitor.SetNode(py_node->node, name, e4_VertexType(vt));
		} else if (PyVertex_Check(PyTuple_GetItem(args, 0))) {
			PyVertex *py_vertex;
			int uvn, uvt;
			if (!PyArg_ParseTuple(args, "Oii", &py_vertex, &uvn, &uvt))
				return 0;
			success = self->visitor.SetVertex(py_vertex->vertex, uvn != 0, uvt != 0);
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	case 4:
		if (PyStorage_Check(PyTuple_GetItem(args, 0))) {
			PyStorage *py_storage;
			const char *name;
			int vt, dc;
			if (!PyArg_ParseTuple(args, "Osii", &py_storage, &name, &vt, &dc))
				return 0;
			success = self->visitor.SetStorage(py_storage->storage, name, e4_VertexType(vt), e4_DetachChoice(dc));
		} else if (PyVertex_Check(PyTuple_GetItem(args, 0))) {
			PyVertex *py_vertex;
			int uvn, uvt, vm;
			if (!PyArg_ParseTuple(args, "Oiii", &py_vertex, &uvn, &uvt, &vm))
				return 0;
			success = self->visitor.SetVertex(py_vertex->vertex, uvn != 0, uvt != 0, e4_VisitMethod(vm));
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	default:
		PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
		break;
	}

	if (!success) {
		PyErr_SetString(e4pyExc_APIFailure, "Set: Cannot set visitor");
		return 0;
	}

	Py_INCREF(Py_None);
	return Py_None;
}

/** PyVertexVisitor_Next.
 *
 */
static PyObject* PyVertexVisitor_Next(PyVertexVisitor* self)
{
	e4_Vertex vertex;
	if (!self->visitor.NextVertex(vertex)) {
		PyErr_SetString(e4pyExc_APIFailure, "Next: No more vertices to visit");
		return 0;
	}

	return PyVertex_FromVertex(vertex);
}

/** PyVertexVisitor_CurrentAndAdvance.
 *
 */
static PyObject* PyVertexVisitor_CurrentAndAdvance(PyVertexVisitor* self)
{
	e4_Vertex vertex;
	if (!self->visitor.CurrentVertexAndAdvance(vertex)) {
		PyErr_SetString(e4pyExc_APIFailure, "CurrentAndAdvance: No more vertices to visit");
		return 0;
	}

	return PyVertex_FromVertex(vertex);
}

/** Method doc */

static char doc_Set[] = "\
Set(storage[, detach-choise])\n\
Visit all attached vertices defined in the storage with optional detached state (detached, attached, both).\n\
Set(storage, name, vertex-type, [, detach-choise])\n\
Visit all attached vertices that have the same name and vertex-type within the storage with optional detached state.\n\
Set(node[, name, vertex-type])\n\
Visit all the vertices in the node optionaly that have the given name and vertex-type.\n\
Set(vertex[, use-vertex-name, use-vertex-type[, visit-menthod]])\n\
Visit all vertices of the same kind as vertex within the storage containing the vertex.\n\
If vertex is detached, the visitor visits only detached vertices. Otherwise it will visit only attached vertices.\n\
If use-vertex-name is true, only vertices with the same name as vertex are visited. If use-vertex-type is true, only vertices with the same vertex-type as vertex are visited.\n\
visit-method: E4_VMNODE-visit higher rank vertices, E4_VMUNKNOWN, E4_VMSTORAGE-all vertices after vertex, E4_VMNODERANDOM-all vertices after vertex, imlpementation dependant.";

static char doc_Next[] = "\
Next() -> Node\n\
Advances to the next node to be visited and returns the node";

static char doc_CurrentAndAdvance[] = "\
CurrentAndAdvance() -> Node\n\
Returns the node currently being visited, advances to the next node to be visited.";

/** Method list */
static PyMethodDef PyVertexVisitorMethods[] = {
	{"Set", (PyCFunction)PyVertexVisitor_Set, METH_VARARGS, doc_Set},
	{"Next", (PyCFunction)PyVertexVisitor_Next, METH_NOARGS, doc_Next},
	{"CurrentAndAdvance", (PyCFunction)PyVertexVisitor_CurrentAndAdvance, METH_NOARGS, doc_CurrentAndAdvance},
	{0, 0, 0, 0}
};


/** Attributes */

/** PyVertexVisitor_get_current.
 *
 */
static PyObject* PyVertexVisitor_get_current(PyVertexVisitor* self, void *)
{
	e4_Vertex vertex;
	if (!self->visitor.CurrentVertex(vertex)) {
		PyErr_SetString(e4pyExc_APIFailure, "current: No current vertex");
		return 0;
	}

	return PyVertex_FromVertex(vertex);
}

/** PyVertexVisitor_get_done.
 *
 */
static PyObject* PyVertexVisitor_get_done(PyVertexVisitor* self, void *)
{
	return PyInt_FromLong(self->visitor.IsDone());
}

/** PyVertexVisitor_get_valid.
 *
 */
static PyObject* PyVertexVisitor_get_valid(PyVertexVisitor* self, void *)
{
	return PyInt_FromLong(self->visitor.IsValid());
}

/** Attribute doc */

static char doc_current[] = "\
Returns the currently visited vertex.";

static char doc_done[] = "\
Returns true if there are no more vertices to visit.";

static char doc_valid[] = "\
Returns true if visitor has a current vertex being visited.";

/** Attribute list */
static PyGetSetDef PyVertexVisitorGetsets[] = {
    {"current", (getter)PyVertexVisitor_get_current, (setter)NULL, doc_current},
    {"done", (getter)PyVertexVisitor_get_done, (setter)NULL, doc_done},
    {"valid", (getter)PyVertexVisitor_get_valid, (setter)NULL, doc_valid},
    {NULL}
};


/** VertexVisitor access */

/** PyVertexVisitor_new.
 *
 */
/*static*/
PyObject* PyVertexVisitor_new(PyObject* o, PyObject* args)
{
	PyVertexVisitor* result = NULL;
	switch (PyTuple_Size(args)) {
	case 0:
		result = (PyVertexVisitor*)PyVertexVisitor_New();
		break;
	case 1: {
		PyObject *obj;
		if (!PyArg_ParseTuple(args, "O", &obj))
			return 0;
		
		if (PyVertexVisitor_Check(obj)) {
			result = (PyVertexVisitor*)PyVertexVisitor_FromVertexVisitor(PyVertexVisitor_AsVertexVisitor(obj));
		} else if (PyStorage_Check(obj)) {
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(PyStorage_AsStorage(obj));
		} else if (PyNode_Check(obj)) {
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(PyNode_AsNode(obj));
		} else if (PyVertex_Check(obj)) {
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(PyVertex_AsVertex(obj));
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	}
	case 2: {
		PyObject *obj;
		int dc;
		if (!PyArg_ParseTuple(args, "O!i", &PyStorageType, &obj, &dc))
			return 0;
		result = (PyVertexVisitor*)PyVertexVisitor_New();
		result->visitor = e4_VertexVisitor(PyStorage_AsStorage(obj), e4_DetachChoice(dc));
		break;
	}
	case 3: 
		if (PyStorage_Check(PyTuple_GetItem(args, 0))) {
			PyStorage *py_storage;
			const char *name;
			int vt;
			if (!PyArg_ParseTuple(args, "Osi", &py_storage, &name, &vt))
				return 0;
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(py_storage->storage, name, e4_VertexType(vt));
		} else if (PyNode_Check(PyTuple_GetItem(args, 0))) {
			PyNode *py_node;
			const char *name;
			int vt;
			if (!PyArg_ParseTuple(args, "Osi", &py_node, &name, &vt))
				return 0;
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(py_node->node, name, e4_VertexType(vt));
		} else if (PyVertex_Check(PyTuple_GetItem(args, 0))) {
			PyVertex *py_vertex;
			int uvn, uvt;
			if (!PyArg_ParseTuple(args, "Oii", &py_vertex, &uvn, &uvt))
				return 0;
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(py_vertex->vertex, uvn != 0, uvt != 0);
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	case 4:
		if (PyStorage_Check(PyTuple_GetItem(args, 0))) {
			PyStorage *py_storage;
			const char *name;
			int dc, vt;
			if (!PyArg_ParseTuple(args, "Oisi", &py_storage, &dc, &name, &vt))
				return 0;
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(py_storage->storage, e4_DetachChoice(dc), name, e4_VertexType(vt));
		} else if (PyVertex_Check(PyTuple_GetItem(args, 0))) {
			PyVertex *py_vertex;
			int uvn, uvt, vm;
			if (!PyArg_ParseTuple(args, "Oiii", &py_vertex, &uvn, &uvt, &vm))
				return 0;
			result = (PyVertexVisitor*)PyVertexVisitor_New();
			result->visitor = e4_VertexVisitor(py_vertex->vertex, uvn != 0, uvt != 0, e4_VisitMethod(vm));
		} else {
			PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
			return 0;
		}
		break;
	default:
		PyErr_SetString(PyExc_TypeError, ErrInvalidArgs);
		break;
	}
	return (PyObject*)result;
}

/** PyVertexVisitor_dealloc.
 *
 */
static void PyVertexVisitor_dealloc(PyVertexVisitor *self)
{
	self->visitor.~e4_VertexVisitor();		//"placement" dtor
	PyObject_DEL(self);
}

/** PyVertexVisitor_compare.
 *
 */
static int PyVertexVisitor_compare(PyVertexVisitor *self, PyObject *rhs)
{
	if (!PyVertexVisitor_Check(rhs))
		return -1;
	return self->visitor == PyVertexVisitor_AsVertexVisitor(rhs) ? 0 : 1;
}

/** PyVertexVisitor_iter.
 *
 */
static PyObject* PyVertexVisitor_iter(PyVertexVisitor *self)
{
	Py_INCREF(self);
	return (PyObject*)self;
}

/** PyVertexVisitor_iternext.
 *
 */
static PyObject* PyVertexVisitor_iternext(PyVertexVisitor *self)
{
	e4_Vertex vertex;
	if (!self->visitor.CurrentVertexAndAdvance(vertex)) {
		PyErr_SetString(PyExc_StopIteration , "next: No more vertices to visit");
		return 0;
	}

	return PyVertex_FromVertex(vertex);
}

/* Type doc */
static char doc_PyVertexVisitor[] = "\
The VertexVisitor class enables a program to iterate over a collection of vertices selected from a storage.";

/** VertexVisitor type */
PyTypeObject PyVertexVisitorType = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,
	"VertexVisitor",
	sizeof(PyVertexVisitor),		/* tp_basicsize */
	0,					/* tp_itemsize */
	(destructor)PyVertexVisitor_dealloc,	/* tp_dealloc */
	0,//(printfunc)PyVertexVisitor_print, /* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	(cmpfunc)PyVertexVisitor_compare,	/* tp_compare */
	(reprfunc)0,		/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,		/* tp_as_mapping */
    0,					/* tp_hash */
    0,					/* tp_call */
    0,					/* tp_str */
    PyObject_GenericGetAttr,	/* tp_getattro */
    PyObject_GenericSetAttr,	/* tp_setattro */
    0,					/* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    doc_PyVertexVisitor,	/* tp_doc */
    0,					/* tp_traverse */
    0,					/* tp_clear */
    0,					/* tp_richcompare */
    0,					/* tp_weaklistoffset */
    (getiterfunc)PyVertexVisitor_iter,		/* tp_iter */
    (iternextfunc)PyVertexVisitor_iternext,		/* tp_iternext */
    PyVertexVisitorMethods,		/* tp_methods */
    0,					/* tp_members */
    PyVertexVisitorGetsets,		/* tp_getset */
};
