#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

/* include this first, before NO_IMPORT_PYGOBJECT is defined */
#include <pygobject.h>
#include <pygtk/pygtk.h>
#include <diacanvas/dia-canvas.h>


/* Dash is transformed to a tuple of floats. */
static PyObject *
diacanvasdashstyle_from_value(const GValue *value)
{
	DiaDashStyle *dash = (DiaDashStyle*) g_value_get_boxed (value);
	PyObject *t;
	guint i;

	if (!dash || !dash->n_dash) {
		Py_INCREF(Py_None);
		return Py_None;
	}

	t = PyTuple_New (dash->n_dash);
	if (!t) {
		PyErr_SetString(PyExc_TypeError,
				"couldn't create dash tuple.");
		return NULL;
	}
	for (i = 0; i < dash->n_dash; i++) {
		if (PyTuple_SetItem(t, i, PyFloat_FromDouble(dash->dash[i])) != 0) {
			PyErr_SetString(PyExc_TypeError,
					"couldn't add a float to the tuple.");
			Py_DECREF (t);
			return NULL;
		}
	}
	return t;
}

static int
diacanvasdashstyle_to_value (GValue *value, PyObject *py_dash)
{
	int len, i;
	PyObject *sitem;
	DiaDashStyle *dash;

	// A dash may be None:
	if (py_dash == Py_None) {
		g_value_set_boxed (value, NULL);
		return 0;
	}

	len = PySequence_Length(py_dash);
	if (len == -1) {
		PyErr_SetString(PyExc_TypeError,
				"argument must be a tuple of floats.");
		return -1;
	}

	dash = g_malloc (sizeof (DiaDashStyle) +
			 sizeof (gdouble) * MAX (0, len - 1));

	dash->n_dash = len;
	for (i = 0; i < len; i++) {
		sitem = PySequence_GetItem(py_dash, i);
		Py_DECREF(sitem);
		sitem = PyNumber_Float(sitem);
		if (sitem)
			dash->dash[i] = PyFloat_AsDouble(sitem);
		else {
			g_free (dash);
			PyErr_Clear();
			PyErr_SetString(PyExc_TypeError,
					"sequence item not a float");
			return -1;
		}
		Py_DECREF(sitem);
	}

	g_value_set_boxed_take_ownership (value, dash);

	return 0;
}

void pydiashape_add_constants (PyObject *module, const gchar *strip_prefix);
void pydiashape_register_classes (PyObject *d);

extern PyMethodDef pydiashape_functions[];

DL_EXPORT(void)
initshape (void)
{
	PyObject *m, *d;

	/* Standard initialization: */
	init_pygobject ();
	init_pygtk ();

	if (!PyImport_ImportModule("diacanvas.geometry")) {
		Py_FatalError("could not import diacanvas.geometry");
		return;
	}

	pyg_register_boxed_custom (DIA_TYPE_DASH_STYLE,
				   diacanvasdashstyle_from_value,
				   diacanvasdashstyle_to_value);

	m = Py_InitModule ("diacanvas.shape", pydiashape_functions);
	d = PyModule_GetDict (m);

	pydiashape_register_classes (d);
	pydiashape_add_constants (m, "DIA_");

	if (PyErr_Occurred ()) {
		Py_FatalError ("can't initialise module diacanvas.shape");
	}
}

