#include "Python.h"
#include "parse_event_handler.h"

static int read_external_dtd;

/*
  These are the external interfaces
*/
char Parse_doc[] = "\
parse(isrc[, readExtDtd[, parseAsEntity]]) -> Document";

PyObject *Domlette_Parse(PyObject *self, PyObject *args, PyObject *kw) {
  PyObject *source, *result;
  int readExtDtd=read_external_dtd, parseAsEntity=0;
  static char *kwlist[] = {"isrc", "readExtDtd", "parseAsEntity", NULL};
  
  if (!PyArg_ParseTupleAndKeywords(args, kw, "O|ii:parse", kwlist,
                                   &source, &readExtDtd, &parseAsEntity))
    return NULL;

#ifdef DEBUG_PARSER
  fprintf(stderr, "Start parsing.\n");
#endif

  result = ParseDocument(source, readExtDtd, parseAsEntity);

#ifdef DEBUG_PARSER
  fprintf(stderr,"Finished parsing\n");
#endif

  return result;
}

char NonvalParse_doc[] = "\
nonvalParse(isrc[, readExtDtd[, parseAsEntity]]) -> Document";

PyObject *Domlette_NonvalParse(PyObject *self, PyObject *args, PyObject *kw)
{
  PyObject *isrc, *readExtDtd=NULL, *parseAsEntity=NULL;
  static char *kwlist[] = {"isrc", "readExtDtd", "parseAsEntity", NULL};
  int read_ext_dtd=read_external_dtd, parse_as_entity=0;
  PyObject *result;

  if (!PyArg_ParseTupleAndKeywords(args, kw, "O|OO:nonvalParse", kwlist, 
                                   &isrc, &readExtDtd, &parseAsEntity))
    return NULL;

  if (readExtDtd) {
    read_ext_dtd = PyObject_IsTrue(readExtDtd);
    if (read_ext_dtd == -1) return NULL;
  }
  if (parseAsEntity) {
    parse_as_entity = PyObject_IsTrue(parseAsEntity);
    if (parse_as_entity == -1) return NULL;
  }

#ifdef DEBUG_PARSER
  fprintf(stderr, "Start parsing.\n");
#endif

  result = ParseDocument(isrc, read_ext_dtd, parse_as_entity);

#ifdef DEBUG_PARSER
  fprintf(stderr,"Finished parsing\n");
#endif

  return result;
}


int DomletteReader_Init(PyObject *module)
{
  PyObject *import, *constant;

  import = PyImport_ImportModule("Ft.Xml");
  if (import == NULL) return -1;

  constant = PyObject_GetAttrString(import, "READ_EXTERNAL_DTD");
  if (constant == NULL) {
    Py_DECREF(import);
    return -1;
  }
  Py_DECREF(import);

  read_external_dtd = PyObject_IsTrue(constant);
  Py_DECREF(constant);
  if (read_external_dtd == -1) return -1;

  return 0;
}

void DomletteReader_Fini(void)
{
  /* no cleanup to perform */
}
