/* Chrysalide - Outil d'analyse de fichiers binaires
 * comparable.c - équivalent Python du fichier "glibext/comparable.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 "comparable.h"


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


#include <glibext/comparable-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_comparable_object_interface_init(GComparableObjectInterface *, gpointer *);

/* Réalise une comparaison étendue entre objets. */
static int py_comparable_object_compare_wrapper(const GComparableObject *, const GComparableObject *);



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


/* Transmet le statut d'une comparaison effectuée par le parent. */
static PyObject *py_comparable_object_parent_compare(PyObject *, PyObject *);

/* Effectue une comparaison avec un objet 'ComparableObject'. */
static PyObject *py_comparable_object_richcompare(PyObject *, PyObject *, int);



/* ---------------------------------------------------------------------------------- */
/*                          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_comparable_object_interface_init(GComparableObjectInterface *iface, gpointer *unused)
{
#define COMPARABLE_OBJECT_DOC                                               \
    "The ComparableObject class provides an interface to compare"           \
    " objects.\n"                                                           \
    "\n"                                                                    \
    "A typical class declaration for a new implementation looks like:\n"    \
    "\n"                                                                    \
    "    class NewImplem(GObject.Object, ComparableObject):\n"              \
    "        ...\n"                                                         \
    "\n"                                                                    \
    "The following method has to be defined for new implementations:\n"     \
    "* pychrysalide.glibext.ComparableObject._compare().\n"

    iface->compare = py_comparable_object_compare_wrapper;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : object = premier objet à consulter pour une comparaison.     *
*                other  = second objet à consulter pour une comparaison.      *
*                                                                             *
*  Description : Réalise une comparaison étendue entre objets.                *
*                                                                             *
*  Retour      : Bilan de la comparaison.                                     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static int py_comparable_object_compare_wrapper(const GComparableObject *object, const GComparableObject *other)
{
    int result;                             /* Bilan à retourner           */
    PyGILState_STATE gstate;                /* Sauvegarde d'environnement  */
    PyObject *pyobj;                        /* Objet Python concerné       */
    PyObject *args;                         /* Arguments pour l'appel      */
    PyObject *pyret;                        /* Bilan de consultation       */

#define COMPARABLE_OBJECT_COMPARE_WRAPPER PYTHON_WRAPPER_DEF        \
(                                                                   \
    _compare, "$self, other",                                       \
    METH_VARARGS,                                                   \
    "Abstract method allowing to compare two objects implementing"  \
    " the interface. This method is used to handle rich comparisons"\
    " automatically.\n"                                             \
    "\n"                                                            \
    "The result has to be an integer lesser than, equal to, or"     \
    " greater than zero if *self* is found, respectively, to be"    \
    " lesser than, to match, or to be greater than *other*.\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));

    args = PyTuple_New(1);
    PyTuple_SetItem(args, 0, pygobject_new(G_OBJECT(other)));

    pyret = run_python_method(pyobj, "_compare", args);

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

        else
            PyErr_SetString(PyExc_TypeError, _("comparison status has to be a signed integer"));

    }

    Py_XDECREF(pyret);

    Py_DECREF(args);

    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 le statut d'une comparaison effectuée par le parent.*
*                                                                             *
*  Retour      : Bilan de la comparaison.                                     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_comparable_object_parent_compare(PyObject *self, PyObject *args)
{
    PyObject *result;                       /* Valeur à retourner          */
    GComparableObject *other;               /* Second objet à comparer     */
    int ret;                                /* Bilan de lecture des args.  */
    GComparableObject *object;              /* Mécanismes natifs           */
    GComparableObjectInterface *iface;      /* Interface utilisée          */
    GComparableObjectInterface *parent_iface; /* Interface parente         */
    int status;                             /* Bilan d'une comparaison     */

#define COMPARABLE_OBJECT_PARENT_COMPARE_METHOD PYTHON_METHOD_DEF   \
(                                                                   \
    parent_compare, "$sel, otherf",                                 \
    METH_VARARGS, py_comparable_object,                             \
    "Provide the comparison status defined by the interface"        \
    " implementation from the object native parent.\n"              \
    "\n"                                                            \
    "The result is a signed integer.\n"                             \
    "\n"                                                            \
    "A *TypeError* exception is raised if the object parent does"   \
    " not implement the pychrysalide.glibext.ComparableObject"      \
    " 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()._compare() function has to be"   \
    " used instead."                                                \
)

    if (!check_for_native_parent(self))
        return NULL;

    ret = PyArg_ParseTuple(args, "O&", convert_to_comparable_object, &other);
    if (!ret) return NULL;

    object = G_COMPARABLE_OBJECT(pygobject_get(self));

    iface = G_COMPARABLE_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 ComparableObject interface"));

        result = NULL;

    }
    else
    {
        status = parent_iface->compare(object, other);

        result = PyLong_FromLong(status);

        CLEAN_RESULT_IF_RAISED_EXCEPTION(result);

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : a  = premier object Python à consulter.                      *
*                b  = second object Python à consulter.                       *
*                op = type de comparaison menée.                              *
*                                                                             *
*  Description : Effectue une comparaison avec un objet 'ComparableObject'.   *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_comparable_object_richcompare(PyObject *a, PyObject *b, int op)
{
    PyObject *result;                       /* Bilan à retourner           */
    int ret;                                /* Bilan de lecture des args.  */
    GComparableObject *obj_a;               /* Instance à manipuler #1     */
    GComparableObject *obj_b;               /* Instance à manipuler #2     */
    int status;                             /* Bilan d'une comparaison     */

    ret = PyObject_IsInstance(b, (PyObject *)get_python_comparable_object_type());
    if (!ret)
    {
        result = Py_NotImplemented;
        goto cmp_done;
    }

    obj_a = G_COMPARABLE_OBJECT(pygobject_get(a));
    obj_b = G_COMPARABLE_OBJECT(pygobject_get(b));

    status = g_comparable_object_compare(obj_a, obj_b);

    switch (op)
    {
        case Py_LT:
            result = (status < 0 ? Py_True : Py_False);
            break;

        case Py_LE:
            result = (status <= 0 ? Py_True : Py_False);
            break;

        case Py_EQ:
            result = (status == 0 ? Py_True : Py_False);
            break;

        case Py_NE:
            result = (status != 0 ? Py_True : Py_False);
            break;

        case Py_GT:
            result = (status > 0 ? Py_True : Py_False);
            break;

        case Py_GE:
            result = (status >= 0 ? Py_True : Py_False);
            break;

        default:
            assert(false);
            result = Py_NotImplemented;
            break;

    }

 cmp_done:

    Py_INCREF(result);

    CLEAN_RESULT_IF_RAISED_EXCEPTION(result);

    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_comparable_object_type(void)
{
    static PyMethodDef py_comparable_object_methods[] = {
        COMPARABLE_OBJECT_COMPARE_WRAPPER,
        COMPARABLE_OBJECT_PARENT_COMPARE_METHOD,
        { NULL }
    };

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

    static PyTypeObject py_comparable_object_type = {

        PyVarObject_HEAD_INIT(NULL, 0)

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

        /**
         * Une valeur de .tp_richcompare non nulle écarte la définition du
         * champ .tp_hash à la valeur par défaut du type PyBaseObject_Type
         * dans les préparatifs de la fonction Python inherit_slots().
         *
         * Ces préparatifs se poursuivent avec type_ready_set_hash(),
         * qui initialise .tp_hash avec PyObject_HashNotImplemented(),
         * qui n'est donc pas un comportement par défaut.
         *
         * Côté PyGObject, la fonction pygobject_inherit_slots() y voit
         * une implémentation de .tp_hash personnalisée, ce qui bloque
         * la défintion d'autres personnalisations, comme celle de
         * l'interface HashableObject.
         *
         * La valeur nominale nulle est ainsi écartée au préalable ici.
         */
        .tp_hash        = (hashfunc)_Py_HashPointer,

        .tp_flags       = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

        .tp_doc         = COMPARABLE_OBJECT_DOC,

        .tp_richcompare = py_comparable_object_richcompare,

        .tp_methods     = py_comparable_object_methods,
        .tp_getset      = py_comparable_object_getseters

    };

    return &py_comparable_object_type;

}


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

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

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

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

    };

    type = get_python_comparable_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_COMPARABLE_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 comparable.          *
*                                                                             *
*  Retour      : Bilan de l'opération, voire indications supplémentaires.     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

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

    result = PyObject_IsInstance(arg, (PyObject *)get_python_comparable_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 comparable object");
            break;

        case 1:
            *((GComparableObject **)dst) = G_COMPARABLE_OBJECT(pygobject_get(arg));
            break;

        default:
            assert(false);
            break;

    }

    return result;

}