#include <string.h>
#include <skunk_query.h>
#include "pyskunk.h"

/* Skunk DB class, encapsulates query methods */
PyMethodDef sdbMethods[] = {
	{"query", (PyCFunction)sdb_query, METH_VARARGS, "Query a record"},
	{NULL, NULL, 0, NULL}
};

/* Type definition for the class */
PyTypeObject skunkdbType = {
	PyObject_HEAD_INIT(NULL)
	0,				/* ob_size */
	"skunkdb",			/* tp_name */
	sizeof(struct sdbObject),	/* tp_size */
	0,				/* tp_itemsize */
	(destructor) sdbDealloc, 	/* tp_dealloc */
	0,				/* tp_print */
	(getattrfunc) sdbGetAttr, 	/* tp_getattr */
	0,				/* tp_setattr */
	0,				/* tp_compare */
	0,				/* tp_repr */
	0,				/* tp_as_number */
	0,				/* tp_as_sequence */
	0,				/* tp_as_mapping */
};


void sdbDealloc(struct sdbObject *s)
{
	sdbq_close(&s->sdb);
	PyMem_DEL(s);
}

PyObject *sdb_query(sdbObject *s, PyObject *args)
{
	PyObject *ret;
	char *buf;
	char *key;

	if (!PyArg_ParseTuple(args, "s", &key)) 
		return NULL;

	if ( sdbq_query(&s->sdb, (u_int8_t *)key, strlen(key))>0 ) {
		if ( !(buf=malloc(s->sdb.item.val_len+1)) ) {
			return 0;
		}
		
		memcpy(buf, s->sdb.item.val, s->sdb.item.val_len);
		buf[s->sdb.item.val_len]='\0';
		
		ret=Py_BuildValue("s", buf);
		free(buf);
		return ret;
	}else return NULL;
}

PyObject * sdbGetAttr(sdbObject *s, char *name) {
	return Py_FindMethod(sdbMethods, (PyObject *)s, name);    
}
