#include "oosxl_module.h"


PyTypeObject DocumentType;

static void Document_dealloc(DocumentObject* self)
{
    if (self->handle)
    {
        doc_release(self->handle);
    }

    Py_TYPE(self)->tp_free((PyObject*)self);
}

static PyObject* Document_get_workbook(DocumentObject* self, PyObject* args)
{
    if (!check_handle(self->handle, "document"))
        return NULL;

    WorkbookHandle wb_handle = doc_get_workbook(self->handle);
    if (wb_handle == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Failed to get workbook");
        return NULL;
    }

    return create_workbook_object(wb_handle);
}

static PyObject* Document_save(DocumentObject* self, PyObject* args)
{
    if (!check_handle(self->handle, "document"))
        return NULL;

    const char* filename = NULL;
    if (!PyArg_ParseTuple(args, "|z", &filename))
    {
        return NULL;
    }

    int result = doc_save(self->handle, filename);
    if (result == 0)
    {
        PyErr_SetString(PyExc_RuntimeError, "Failed to save document");
        return NULL;
    }

    Py_RETURN_NONE;
}

static PyMethodDef Document_methods[] = {
    {"get_workbook", (PyCFunction)Document_get_workbook, METH_NOARGS, "Get workbook from document"},
    {"save", (PyCFunction)Document_save, METH_VARARGS, "Save document to file(optional filename)"},
    {NULL} /* Sentinel */
};

PyTypeObject DocumentType = {
    PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "oosxl.Document",
    .tp_doc = "Document object",
    .tp_basicsize = sizeof(DocumentObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
    .tp_dealloc = (destructor)Document_dealloc,
    .tp_methods = Document_methods,
};

PyObject* create_document_object(DocumentHandle handle)
{
    DocumentObject* obj = (DocumentObject*)PyObject_New(DocumentObject, &DocumentType);
    if (obj != NULL)
    {
        obj->handle = handle;
    }
    return (PyObject*)obj;
}
