"""Credentials Import/Export Extension"""
GSSAPI="BASE"  # This ensures that a full module is generated by Cython

from gssapi.raw.cython_types cimport *
from gssapi.raw.cython_converters cimport c_create_oid_set
from gssapi.raw.cython_converters cimport c_get_mech_oid_set
from gssapi.raw.cython_converters cimport c_py_ttl_to_c, c_c_ttl_to_py
from gssapi.raw.creds cimport Creds
from gssapi.raw.names cimport Name
from gssapi.raw.oids cimport OID

from gssapi.raw.misc import GSSError
from gssapi.raw.named_tuples import AcquireCredResult, AddCredResult


cdef extern from "python_gssapi_ext.h":
    OM_uint32 gss_export_cred(OM_uint32 *min_stat, gss_cred_id_t cred_handle,
                              gss_buffer_t token) nogil

    OM_uint32 gss_import_cred(OM_uint32 *min_stat, gss_buffer_t token,
                              gss_cred_id_t *cred_handle) nogil


def export_cred(Creds creds not None):
    """
    export_cred(creds)
    Export GSSAPI credentials.

    This method exports GSSSAPI credentials into a token
    which may be transmitted between different processes.

    Args:
        creds (Creds): the credentials object to be exported

    Returns:
        bytes: the exported token representing the given credentials object

    Raises:
        GSSError
    """

    # GSS_C_EMPTY_BUFFER
    cdef gss_buffer_desc exported_creds = gss_buffer_desc(0, NULL)

    cdef OM_uint32 maj_stat, min_stat

    with nogil:
        maj_stat = gss_export_cred(&min_stat, creds.raw_creds, &exported_creds)

    if maj_stat == GSS_S_COMPLETE:
        res = (<char*>exported_creds.value)[:exported_creds.length]
        gss_release_buffer(&min_stat, &exported_creds)
        return res
    else:
        raise GSSError(maj_stat, min_stat)


def import_cred(token not None):
    """
    import_cred(token)
    Import GSSAPI credentials from a token.

    This method imports a credentials object from a token
    previously exported by :func:`export_cred`.

    Args:
        token (bytes): the token to import

    Returns:
        Creds: the imported credentials object

    Raises:
        GSSError
    """

    cdef gss_buffer_desc token_buffer = gss_buffer_desc(len(token), token)

    cdef gss_cred_id_t creds

    cdef OM_uint32 maj_stat, min_stat

    with nogil:
        maj_stat = gss_import_cred(&min_stat, &token_buffer, &creds)

    cdef Creds res
    if maj_stat == GSS_S_COMPLETE:
        res = Creds()
        res.raw_creds = creds
        return res
    else:
        raise GSSError(maj_stat, min_stat)
