/* Chrysalide - Outil d'analyse de fichiers binaires
 * hashable.c - équivalent Python du fichier "glibext/hashable.c"
 *
 * Copyright (C) 2025 Cyrille Bagard
 *
 *  This file is part of Chrysalide.
 *
 *  Chrysalide is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Chrysalide is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


#include "hashable.h"


#include <assert.h>
#include <pygobject.h>


#include <glibext/hashable-int.h>


#include "../access.h"
#include "../helpers.h"



/* ------------------------ GLUE POUR CREATION DEPUIS PYTHON ------------------------ */


/* Procède à l'initialisation de l'interface de détermination. */
static void py_hashable_object_interface_init(GHashableObjectInterface *, gpointer *);

/* Calcule l'empreinte sur 32 bits d'un objet. */
static guint py_hashable_object_hash_wrapper(const GHashableObject *);



/* ------------------------- CONNEXION AVEC L'API DE PYTHON ------------------------- */


/* Transmet l'empreinte d'un objet calculée par son parent. */
static PyObject *py_hashable_object_parent_hash(PyObject *, PyObject *);

/* Calcule l'empreinte sur 32 bits d'un objet. */
static Py_hash_t py_hashable_object_hash(PyObject *);



/* ---------------------------------------------------------------------------------- */
/*                          GLUE POUR CREATION DEPUIS PYTHON                          */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : iface  = interface GLib à initialiser.                       *
*                unused = adresse non utilisée ici.                           *
*                                                                             *
*  Description : Procède à l'initialisation de l'interface de détermination.  *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void py_hashable_object_interface_init(GHashableObjectInterface *iface, gpointer *unused)
{
#define HASHABLE_OBJECT_DOC                                                 \
    "The HashableObject class defines a interface ensuring that a"          \
    " customized hashing method is available for an object.\n"              \
    "\n"                                                                    \
    "A typical class declaration for a new implementation looks like:\n"    \
    "\n"                                                                    \
    "    class NewImplem(GObject.Object, HashableObject):\n"                \
    "        ...\n"                                                         \
    "\n"                                                                    \
    "The following method has to be defined for new implementations:\n"     \
    "* pychrysalide.glibext.HashableObject._hash().\n"

    iface->hash = py_hashable_object_hash_wrapper;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : object = objet dont l'instance est à consulter.              *
*                                                                             *
*  Description : Calcule l'empreinte sur 32 bits d'un objet.                  *
*                                                                             *
*  Retour      : Valeur de représentation, unique pour l'objet ou non.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static guint py_hashable_object_hash_wrapper(const GHashableObject *object)
{
    guint result;                       /* Valeur à retourner              */
    PyGILState_STATE gstate;                /* Sauvegarde d'environnement  */
    PyObject *pyobj;                        /* Objet Python concerné       */
    PyObject *pyret;                        /* Bilan de consultation       */

#define HASHABLE_OBJECT_HASH_WRAPPER PYTHON_WRAPPER_DEF             \
(                                                                   \
    _hash, "$self",                                                 \
    METH_NOARGS,                                                    \
    "Abstract method computing a hash from an object which is used" \
    " as the default implementation of the __hash__() method.\n"    \
    "\n"                                                            \
    "The result has to be an unsigned integer.\n"                   \
    "\n"                                                            \
    "A *TypeError* exception is raised if the return value is not"  \
    " an integer."                                                  \
)

    result = 0;

    gstate = PyGILState_Ensure();

    pyobj = pygobject_new(G_OBJECT(object));

    pyret = run_python_method(pyobj, "_hash", NULL);

    if (pyret != NULL)
    {
        if (PyLong_Check(pyret))
            result = PyLong_AsUnsignedLong(pyret);

        else
            PyErr_SetString(PyExc_TypeError, _("computed hash value has to be an unsigned integer"));

    }

    Py_XDECREF(pyret);

    Py_DECREF(pyobj);

    PyGILState_Release(gstate);

    return result;

}



/* ---------------------------------------------------------------------------------- */
/*                           CONNEXION AVEC L'API DE PYTHON                           */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : self = objet dont l'instance se veut unique.                 *
*                args = adresse non utilisée ici.                             *
*                                                                             *
*  Description : Transmet l'empreinte d'un objet calculée par son parent.     *
*                                                                             *
*  Retour      : Valeur de représentation, unique pour l'objet ou non.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_hashable_object_parent_hash(PyObject *self, PyObject *args)
{
    PyObject *result;                       /* Valeur à retourner          */
    GHashableObject *object;                /* Mécanismes natifs           */
    GHashableObjectInterface *iface;        /* Interface utilisée          */
    GHashableObjectInterface *parent_iface; /* Interface parente           */
    guint hash;                             /* Valeur d'empreitne          */

#define HASHABLE_OBJECT_PARENT_HASH_METHOD PYTHON_METHOD_DEF        \
(                                                                   \
    parent_hash, "$self",                                           \
    METH_NOARGS, py_hashable_object,                                \
    "Provide the hash value defined by the interface implementation"\
    " from the object native parent.\n"                             \
    "\n"                                                            \
    "The result is an unsigned integer.\n"                          \
    "\n"                                                            \
    "A *TypeError* exception is raised if the object parent does"   \
    " not implement the pychrysalide.glibext.HashableObject"        \
    " interface.\n"                                                 \
    "\n"                                                            \
    "A *RuntimeError* exception is raised if the direct parent type"\
    " of the object has not a native implementation. For Python"    \
    " implementations, the super()._hash() function has to be used" \
    " instead."                                                     \
)

    if (!check_for_native_parent(self))
        return NULL;

    object = G_HASHABLE_OBJECT(pygobject_get(self));

    iface = G_HASHABLE_OBJECT_GET_IFACE(object);

    parent_iface = g_type_interface_peek_parent(iface);

    if (parent_iface == NULL)
    {
        PyErr_SetString(PyExc_TypeError, _("object parent does not implement the HashableObject interface"));

        result = NULL;

    }
    else
    {
        hash = parent_iface->hash(object);

        result = PyLong_FromUnsignedLong(hash);

        CLEAN_RESULT_IF_RAISED_EXCEPTION(result);

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self = objet manipulé ici.                                   *
*                                                                             *
*  Description : Calcule l'empreinte sur 32 bits d'un objet.                  *
*                                                                             *
*  Retour      : Valeur de représentation, unique pour l'objet ou non.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static Py_hash_t py_hashable_object_hash(PyObject *self)
{
    Py_hash_t result;                       /* Empreinte à retourner       */
    GHashableObject *object;                /* Mécanismes natifs           */

    object = G_HASHABLE_OBJECT(pygobject_get(self));

    result = g_hashable_object_hash(object);

    UPDATE_RESULT_IF_RAISED_EXCEPTION(-1);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : -                                                            *
*                                                                             *
*  Description : Fournit un accès à une définition de type à diffuser.        *
*                                                                             *
*  Retour      : Définition d'objet pour Python.                              *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

PyTypeObject *get_python_hashable_object_type(void)
{
    static PyMethodDef py_hashable_object_methods[] = {
        HASHABLE_OBJECT_HASH_WRAPPER,
        HASHABLE_OBJECT_PARENT_HASH_METHOD,
        { NULL }
    };

    static PyGetSetDef py_hashable_object_getseters[] = {
        { NULL }
    };

    static PyTypeObject py_hashable_object_type = {

        PyVarObject_HEAD_INIT(NULL, 0)

        .tp_name        = "pychrysalide.glibext.HashableObject",
        .tp_basicsize   = sizeof(PyObject),

        .tp_hash        = py_hashable_object_hash,

        .tp_flags       = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

        .tp_doc         = HASHABLE_OBJECT_DOC,

        .tp_methods     = py_hashable_object_methods,
        .tp_getset      = py_hashable_object_getseters,

    };

    return &py_hashable_object_type;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : -                                                            *
*                                                                             *
*  Description : Prend en charge l'objet 'pychrysalide.....HashableObject'.   *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool ensure_python_hashable_object_is_registered(void)
{
    PyTypeObject *type;                     /* Type Python 'HashableObject'*/
    PyObject *module;                       /* Module à recompléter        */
    PyObject *dict;                         /* Dictionnaire du module      */

    static GInterfaceInfo info = {          /* Paramètres d'inscription    */

        .interface_init = (GInterfaceInitFunc)py_hashable_object_interface_init,
        .interface_finalize = NULL,
        .interface_data = NULL,

    };

    type = get_python_hashable_object_type();

    if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
    {
        module = get_access_to_python_module("pychrysalide.glibext");

        dict = PyModule_GetDict(module);

        if (!register_interface_for_pygobject(dict, G_TYPE_HASHABLE_OBJECT, type, &info))
            return false;

    }

    return true;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : arg = argument quelconque à tenter de convertir.             *
*                dst = destination des valeurs récupérées en cas de succès.   *
*                                                                             *
*  Description : Tente de convertir en interface d'objet réductible.          *
*                                                                             *
*  Retour      : Bilan de l'opération, voire indications supplémentaires.     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

int convert_to_hashable_object(PyObject *arg, void *dst)
{
    int result;                             /* Bilan à retourner           */

    result = PyObject_IsInstance(arg, (PyObject *)get_python_hashable_object_type());

    switch (result)
    {
        case -1:
            /* L'exception est déjà fixée par Python */
            result = 0;
            break;

        case 0:
            PyErr_SetString(PyExc_TypeError, "unable to convert the provided argument to hashable object");
            break;

        case 1:
            *((GHashableObject **)dst) = G_HASHABLE_OBJECT(pygobject_get(arg));
            break;

        default:
            assert(false);
            break;

    }

    return result;

}