#define PY_SSIZE_T_CLEAN
#include <Python.h>

#include "cmunipack.h"
#include "ccdfileclass.h"

PyObject *cmpack_error(int code);
PyObject *err_closed(void);

typedef struct {
    PyObject_HEAD
	CmpackMasterFlat *f;
} MasterFlat;

static PyObject *
MasterFlat_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    MasterFlat *self = (MasterFlat*)type->tp_alloc(type, 0);
	if (self != NULL)
		self->f = NULL;
    return (PyObject *)self;
}

static void
MasterFlat_dealloc(MasterFlat* self)
{
	if (self->f)
		cmpack_mflat_destroy(self->f);
    self->ob_base.ob_type->tp_free((PyObject*)self);
}

static int
MasterFlat_init(MasterFlat *self, PyObject *args, PyObject *kwds)
{
	int res, format = CMPACK_BITPIX_AUTO;
	double minvalue = 0.0, maxvalue = 65535.0, level = 10000.0;
	CmpackBorder b;
	PyObject *output, *border = NULL;

	static char *kwlist[] = {"output", "format", "border", "minvalue", "maxvalue", "level", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|iO!ddd", kwlist, &CCDFileType, &output, 
		&format, &PyTuple_Type, &border, &minvalue, &maxvalue, &level))
        return -1;

	if (!self->f) {
		self->f = cmpack_mflat_init();
		if (!self->f) {
			PyErr_SetString(PyExc_MemoryError, "Memory allocation error");
			return -1;
		}
	}
	res = cmpack_mflat_open(self->f, ((CCDFile*)output)->f);
	if (res!=0) {
		cmpack_error(res);
		return -1;
	}
	cmpack_mflat_set_bitpix(self->f, format);
	if (border) {
		if (!PyArg_ParseTuple(border, "iiii", &b.left, &b.top, &b.right, &b.bottom)) 
			return -1;
		cmpack_mflat_set_border(self->f, &b);
	}
	cmpack_mflat_set_minvalue(self->f, minvalue);
	cmpack_mflat_set_maxvalue(self->f, maxvalue);
	cmpack_mflat_set_level(self->f, level);
	return 0;
}

static PyObject *
MasterFlat_flush(MasterFlat *self, PyObject *args)
{
	if (self->f) {
		int res = cmpack_mflat_close(self->f);
		self->f = NULL;
		if (res!=0)
			return cmpack_error(res);
	}
	Py_RETURN_NONE;
}

static PyObject *
MasterFlat_border(MasterFlat *self, void *data)
{
	CmpackBorder b;
	cmpack_mflat_get_border(self->f, &b);
	return Py_BuildValue("iiii", b.left, b.top, b.right, b.bottom);
}

static PyObject *
MasterFlat_format(MasterFlat *self, void *data)
{
	return PyLong_FromLong(cmpack_mflat_get_bitpix(self->f));
}

static PyObject *
MasterFlat_level(MasterFlat *self, void *data)
{
	return PyFloat_FromDouble(cmpack_mflat_get_level(self->f));
}

static PyObject *
MasterFlat_minvalue(MasterFlat *self, void *data)
{
	return PyFloat_FromDouble(cmpack_mflat_get_minvalue(self->f));
}

static PyObject *
MasterFlat_maxvalue(MasterFlat *self, void *data)
{
	return PyFloat_FromDouble(cmpack_mflat_get_maxvalue(self->f));
}

static PyObject *
MasterFlat_add(MasterFlat *self, PyObject *param)
{
	int res;

	if (!CCDFile_Check(param)) {
		/* Other types */
		PyErr_SetString(PyExc_TypeError, "Frame should be a CCDFile object.");
		return NULL;
	}

	res = cmpack_mflat_read(self->f, ((CCDFile*)param)->f);
	if (res!=0) {
		cmpack_error(res);
		return NULL;
	}
	Py_RETURN_NONE;
}

static PyGetSetDef MasterFlat_getset[] = {
	{"format", (getter)MasterFlat_format, NULL, 
	"Image border size in pixels"},
	{"level", (getter)MasterFlat_level, NULL, 
	"Ouput mean level in ADU"},
	{"border", (getter)MasterFlat_border, NULL, 
	"Image border size in pixels"},
	{"minvalue", (getter)MasterFlat_minvalue, NULL, 
	"Threshold for \"invalid\" pixel values"},
	{"maxvalue", (getter)MasterFlat_maxvalue, NULL, 
	"Threshold for \"overexposed\" pixels"},
	{NULL}
};

static PyMethodDef MasterFlat_methods[] = {
	{"flush", (PyCFunction)MasterFlat_flush, METH_NOARGS,
	"Close file"},
	{"add", (PyCFunction)MasterFlat_add, METH_O,
	"Add a frame"},
    {NULL}  /* Sentinel */
};

PyTypeObject MasterFlatType = {
    PyObject_HEAD_INIT(NULL)
    .tp_name = "cmpack.MasterFlat",          /*tp_name*/
    .tp_basicsize = sizeof(MasterFlat),           /*tp_basicsize*/
    .tp_dealloc = (destructor)MasterFlat_dealloc,           /*tp_dealloc*/
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,        /*tp_flags*/
    .tp_doc = "MasterFlat correction",        /* tp_doc */
    .tp_methods = MasterFlat_methods,           /* tp_methods */
    .tp_getset = MasterFlat_getset,            /* tp_getset */
    .tp_init = (initproc)MasterFlat_init,      /* tp_init */
    .tp_new = MasterFlat_new                 /* tp_new */
};
