/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* NSPR header files */
#undef HAVE_LONG_LONG           /* FIXME: both Python.h and nspr.h define HAVE_LONG_LONG  */
#include "nspr.h"
#include "prerror.h"

typedef struct {
    PyObject     *nspr_exception;
    PyObject     *(*set_nspr_error)(const char *format, ...);
    PyObject     *(*tuple_str)(PyObject *tuple);
} PyNSPR_ERROR_C_API_Type;

#ifdef NSS_ERROR_MODULE

#else  /* not NSS_ERROR_MODULE */

static PyNSPR_ERROR_C_API_Type nspr_error_c_api;

#define set_nspr_error (*nspr_error_c_api.set_nspr_error)
#define tuple_str (*nspr_error_c_api.tuple_str)

static int
import_nspr_error_c_api(void)
{
    PyObject *module = NULL;
    PyObject *c_api_object = NULL;
    void *api = NULL;

    if ((module = PyImport_ImportModule("nss.error")) == NULL)
        return -1;

    if ((c_api_object = PyObject_GetAttrString(module, "_C_API")) == NULL) {
        Py_DECREF(module);
        return -1;
    }

    if (!(PyCObject_Check(c_api_object))) {
        Py_DECREF(c_api_object);
        Py_DECREF(module);
        return -1;
    }

    if ((api = PyCObject_AsVoidPtr(c_api_object)) == NULL) {
        Py_DECREF(c_api_object);
        Py_DECREF(module);
        return -1;
    }

    memcpy(&nspr_error_c_api, api, sizeof(nspr_error_c_api));
    Py_DECREF(c_api_object);
    Py_DECREF(module);
    return 0;
}

#endif /* NSS_ERROR_MODULE */
