#include <python2.1/Python.h> /* should be modified to be pythonX.Y */
#include <stdio.h>
#include <unistd.h>

#include "structs.h"
#include "macro.h"

/* first declare static functions */

struct wlp_list_t *list;

static FILE *fd = NULL;

static PyObject *node2dict(struct wlp_node_t *node);

static PyObject *wlp_setfilebyname(PyObject *self, PyObject *args) {
	char *file;

	DBG("setfilebyname\n");
	if (!PyArg_ParseTuple(args, "s", &file))
		return NULL;

	fd = fopen(file,"r");

	return Py_None;
}

static PyObject *wlp_setfilebyfd(PyObject *self, PyObject *args) {
	PyObject *file = NULL;
	
        if (!PyArg_ParseTuple(args, "O", &file))
		return NULL;

	if(!file)
		return NULL;

	if(!PyFile_Check(file))
		return NULL;

	fd = PyFile_AsFile(file);

	return Py_None;
	
}



static PyObject *wlp_mklist(PyObject *self, PyObject *args) {
	struct wlp_node_t *tmp;
	int count;

	PyObject *pylist = NULL;

	DBG("a\n");
	parse(fd);

	DBG("count %d\n"list->count);
	pylist = PyList_New(0);

	DBG("a\n");
	if(!pylist)
		return NULL;
	
	DBG("a\n");
	if(list)
		for(tmp = list->head, count=0;
		    tmp != list->head || count == 0;
		    tmp = tmp->next, count++) {
			DBG("FOUND(%d) '%s' ('%s': '%s')\n",count,tmp->owner,tmp->left,tmp->right);
			if(PyList_Append(pylist,node2dict(tmp))==-1) {
				DBG("List failed\n");
				return NULL;
			}
			DBG("a\n");
		}

	return pylist;
}


static PyObject *node2dict(struct wlp_node_t *node) {
	PyObject *dict = PyDict_New();

	if(!dict)
		return NULL;
	
	PyDict_SetItem(dict,
		Py_BuildValue("s","owner"),
		Py_BuildValue("s",node->owner));
	
	PyDict_SetItem(dict,
		Py_BuildValue("s",node->left),
		Py_BuildValue("s",node->right));

	return dict;

}

/* second a table with methods/functions matching  */

static PyMethodDef wlp_methods[] = {
	{"mklist", wlp_mklist, METH_VARARGS},
	{"setfilebyname", wlp_setfilebyname, METH_VARARGS},
	{"setfilebyfd", wlp_setfilebyfd, METH_VARARGS},
	{NULL,NULL}
};


/* last the init function, the only one non-static */

void initwlp() {
	(void) Py_InitModule("wlp",wlp_methods);
}
