/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2017)
  
	Adresses mèl :
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Damien
	CALISTE, laboratoire L_Sim, (2017)

	E-mail addresses :
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/

#include <extraFunctions/sfieldbinary.h>

/**
 * SECTION:sfieldbinary
 * @short_description: Defines a specialised #VisuScalarField class
 * that is the result of a binary operation.
 *
 * <para>This class allows to define scalarfields as a result of a
 * binary operation over two scalar fields without allocating any new
 * memory for the new scalar field. The resultig scalar field is also
 * automatically updated whenever any of the source scalar field are
 * changed.</para>
 */

struct _VisuScalarFieldBinaryOpPrivate
{
  gboolean dispose_has_run;

  VisuScalarFieldBinaryOpTypes op;
  double lvalue, rvalue;
  VisuScalarField *lfield, *rfield;
  gulong lchanged, rchanged, lempty, rempty;

  gboolean mmdirty;
  double minmax[2];
};

static void visu_scalar_field_binary_op_dispose(GObject* obj);
static void visu_boxed_interface_init (VisuBoxedInterface *iface);
static gboolean _isEmpty(const VisuScalarField *field);
static void _getGridSize(const VisuScalarField *field, guint grid[3]);
static double _getAt(const VisuScalarField *field, int i, int j, int k);
static gboolean _getValue(const VisuScalarField *field, float xyz[3],
                          double *value, float extension[3]);
static void _getMinMax(const VisuScalarField *field, double minmax[2]);
static VisuBox* _getBox(VisuBoxed *boxed);
static gboolean _setBox(VisuBoxed *self, VisuBox *box);

G_DEFINE_TYPE_WITH_CODE(VisuScalarFieldBinaryOp, visu_scalar_field_binary_op,
                        VISU_TYPE_SCALAR_FIELD,
                        G_ADD_PRIVATE(VisuScalarFieldBinaryOp)
                        G_IMPLEMENT_INTERFACE(VISU_TYPE_BOXED,
                                              visu_boxed_interface_init))

static void visu_scalar_field_binary_op_class_init(VisuScalarFieldBinaryOpClass *klass)
{
  DBG_fprintf(stderr, "VisuScalarFieldBinaryOp: creating the class of the object.\n");

  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* Connect freeing methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_scalar_field_binary_op_dispose;
  VISU_SCALAR_FIELD_CLASS(klass)->isEmpty = _isEmpty;
  VISU_SCALAR_FIELD_CLASS(klass)->getGridSize = _getGridSize;
  VISU_SCALAR_FIELD_CLASS(klass)->getAt = _getAt;
  VISU_SCALAR_FIELD_CLASS(klass)->getValue = _getValue;
  VISU_SCALAR_FIELD_CLASS(klass)->getMinMax = _getMinMax;
}
static void visu_boxed_interface_init(VisuBoxedInterface *iface)
{
  iface->get_box = _getBox;
  iface->set_box = _setBox;
}

static void visu_scalar_field_binary_op_init(VisuScalarFieldBinaryOp *obj)
{
  DBG_fprintf(stderr, "VisuScalarFieldBinaryOp: creating a new scalar field operator (%p).\n", (gpointer)obj);

  obj->priv = visu_scalar_field_binary_op_get_instance_private(obj);

  obj->priv->dispose_has_run = FALSE;

  obj->priv->lfield = (VisuScalarField*)0;
  obj->priv->rfield = (VisuScalarField*)0;
  obj->priv->mmdirty = TRUE;
  obj->priv->minmax[0] = G_MAXFLOAT;
  obj->priv->minmax[1] = -G_MAXFLOAT;
}
static void visu_scalar_field_binary_op_dispose(GObject* obj)
{
  VisuScalarFieldBinaryOp *self = VISU_SCALAR_FIELD_BINARY_OP(obj);
  DBG_fprintf(stderr, "VisuScalarFieldBinaryOp: dispose object %p.\n", (gpointer)obj);

  if (self->priv->dispose_has_run)
    return;
  self->priv->dispose_has_run = TRUE;

  visu_scalar_field_binary_op_setLeftField(self, (VisuScalarField*)0);
  visu_scalar_field_binary_op_setRightField(self, (VisuScalarField*)0);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_scalar_field_binary_op_parent_class)->dispose(obj);
}

static void _setOp(VisuScalarFieldBinaryOp *field, VisuScalarFieldBinaryOpTypes op)
{
  field->priv->op = op;
  field->priv->lvalue = (op == VISU_OPERATOR_ADDITION || op == VISU_OPERATOR_DIFFERENCE) ? 0. : 1.;
  field->priv->rvalue = (op == VISU_OPERATOR_ADDITION || op == VISU_OPERATOR_DIFFERENCE) ? 0. : 1.;
}

static gboolean _isEmpty(const VisuScalarField *field)
{
  VisuScalarFieldBinaryOp *self;
  gboolean lEmpty, rEmpty;

  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(field), TRUE);

  self = VISU_SCALAR_FIELD_BINARY_OP(field);
  lEmpty = (self->priv->lfield) ? visu_scalar_field_isEmpty(self->priv->lfield) : FALSE;
  rEmpty = (self->priv->rfield) ? visu_scalar_field_isEmpty(self->priv->rfield) : FALSE;
  return lEmpty || rEmpty;
}

static void _getGridSize(const VisuScalarField *field, guint grid[3])
{
  VisuScalarFieldBinaryOp *self;

  g_return_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(field));

  self = VISU_SCALAR_FIELD_BINARY_OP(field);
  if (self->priv->lfield)
    visu_scalar_field_getGridSize(self->priv->lfield, grid);
  else if (self->priv->rfield)
    visu_scalar_field_getGridSize(self->priv->rfield, grid);
}
static double _getAt(const VisuScalarField *field, int i, int j, int k)
{
  VisuScalarFieldBinaryOp *self;
  double lval, rval;
  
  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(field), 0.);

  self = VISU_SCALAR_FIELD_BINARY_OP(field);
  lval = (self->priv->lfield) ? visu_scalar_field_getAt(self->priv->lfield, i, j, k) : self->priv->lvalue;
  rval = (self->priv->rfield) ? visu_scalar_field_getAt(self->priv->rfield, i, j, k) : self->priv->rvalue;
  switch(self->priv->op)
    {
    case VISU_OPERATOR_ADDITION:
      return lval + rval;
    case VISU_OPERATOR_DIFFERENCE:
      return lval - rval;
    case VISU_OPERATOR_PRODUCT:
      return lval * rval;
    case VISU_OPERATOR_RATIO:
      return lval / rval;
    }
  return 0.;
}
static gboolean _getValue(const VisuScalarField *field, float xyz[3],
                          double *value, float extension[3])
{
  VisuScalarFieldBinaryOp *self;
  double lval, rval;
  gboolean lret, rret;
  
  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(field), FALSE);
  
  self = VISU_SCALAR_FIELD_BINARY_OP(field);
  lval = self->priv->lvalue;;
  if (self->priv->lfield)
    lret = visu_scalar_field_getValue(self->priv->lfield, xyz, &lval, extension);
  else
    lret = TRUE;
  rval = self->priv->rvalue;
  if (self->priv->rfield)
    rret = visu_scalar_field_getValue(self->priv->rfield, xyz, &rval, extension);
  else
    rret = TRUE;
  switch(self->priv->op)
    {
    case VISU_OPERATOR_ADDITION:
      *value = lval + rval;
      return lret && rret;
    case VISU_OPERATOR_DIFFERENCE:
      *value = lval - rval;
      return lret && rret;
    case VISU_OPERATOR_PRODUCT:
      *value = lval * rval;
      return lret && rret;
    case VISU_OPERATOR_RATIO:
      *value = lval / rval;
      return lret && rret;
    }
  return FALSE;
}

static void _computeMinMax(VisuScalarFieldBinaryOp *op)
{
  guint grid[3], i, j, k;
  double v;
  VisuScalarField *field;

  op->priv->minmax[0] = G_MAXFLOAT;
  op->priv->minmax[1] = -G_MAXFLOAT;
  field = VISU_SCALAR_FIELD(op);
  _getGridSize(field, grid);
  for (i = 0; i < grid[0]; i++)
    for (j = 0; j < grid[1]; j++)
      for (k = 0; k < grid[2]; k++)
        {
          v = _getAt(field, i, j, k);
          if (v < op->priv->minmax[0]) op->priv->minmax[0] = v;
          if (v > op->priv->minmax[1]) op->priv->minmax[1] = v;
        }
  DBG_fprintf(stderr, "VisuScalarFieldBinaryOp: computing min / max to %g / %g.\n ",
              op->priv->minmax[0], op->priv->minmax[1]);
  op->priv->mmdirty = FALSE;
}

static void _getMinMax(const VisuScalarField *field, double minmax[2])
{
  VisuScalarFieldBinaryOp *self;
  
  g_return_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(field));
  
  self = VISU_SCALAR_FIELD_BINARY_OP(field);
  if (self->priv->mmdirty)
    _computeMinMax(self);
  minmax[0] = self->priv->minmax[0];
  minmax[1] = self->priv->minmax[1];
}

static void emitEmpty(VisuScalarFieldBinaryOp *op)
{
  DBG_fprintf(stderr, "Visu ScalarFieldBinaryOp: %p caught 'empty' notify.\n",
              (gpointer)op);
  if (_isEmpty(VISU_SCALAR_FIELD(op)) || op->priv->dispose_has_run)
    return;
  g_object_notify(G_OBJECT(op), "empty");
}

static void emitChanged(VisuScalarFieldBinaryOp *op)
{
  DBG_fprintf(stderr, "Visu ScalarFieldBinaryOp: %p caught 'changed' signal.\n",
              (gpointer)op);
  op->priv->mmdirty = TRUE;
  if (_isEmpty(VISU_SCALAR_FIELD(op)) || op->priv->dispose_has_run)
    return;
  g_signal_emit_by_name(op, "changed");
}

static gboolean _setBox(VisuBoxed *self, VisuBox *box)
{
  VisuScalarFieldBinaryOp *op;
  gboolean lstatus, rstatus;

  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(self), FALSE);
  op = VISU_SCALAR_FIELD_BINARY_OP(self);

  DBG_fprintf(stderr, "Visu ScalarFieldBinaryOp: set the bounding box to %p.\n", (gpointer)box);
  lstatus = FALSE;
  if (op->priv->lfield)
    lstatus = VISU_BOXED_GET_INTERFACE(op->priv->lfield)->set_box(VISU_BOXED(op->priv->lfield), box);
  rstatus = FALSE;
  if (op->priv->rfield)
    rstatus = VISU_BOXED_GET_INTERFACE(op->priv->rfield)->set_box(VISU_BOXED(op->priv->rfield), box);

  return lstatus || rstatus;
}

static VisuBox* _getBox(VisuBoxed *boxed)
{
  VisuScalarFieldBinaryOp *op;

  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(boxed), (VisuBox*)0);
  op = VISU_SCALAR_FIELD_BINARY_OP(boxed);

  if (op->priv->lfield)
    return visu_boxed_getBox(VISU_BOXED(op->priv->lfield));
  if (op->priv->rfield)
    return visu_boxed_getBox(VISU_BOXED(op->priv->rfield));
  
  return (VisuBox*)0;
}

/**
 * visu_scalar_field_binary_op_new:
 * @op: the type of binary operator.
 * @a: a #VisuScalarField object.
 * @b: a #VisuScalarField object.
 *
 * Create a new #VisuScalarField object as the operation between
 * scalar field @a and @b.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuScalarFieldBinaryOp
 * object.
 */
VisuScalarField* visu_scalar_field_binary_op_new(VisuScalarFieldBinaryOpTypes op,
                                                 VisuScalarField *a,
                                                 VisuScalarField *b)
{
  VisuScalarFieldBinaryOp *field;
  
  field = g_object_new(VISU_TYPE_SCALAR_FIELD_BINARY_OP,
                       "label", "binary op", NULL);
  _setOp(field, op);
  visu_scalar_field_binary_op_setLeftField(field, a);
  visu_scalar_field_binary_op_setRightField(field, b);

  return VISU_SCALAR_FIELD(field);
}

/**
 * visu_scalar_field_binary_op_new_withLeftConst:
 * @op: the type of binary operator.
 * @lValue: a constant.
 * @b: a #VisuScalarField object.
 *
 * Like visu_scalar_field_binary_op_new() but with the left member
 * being a constant.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuScalarFieldBinaryOp
 * object.
 **/
VisuScalarField* visu_scalar_field_binary_op_new_withLeftConst(VisuScalarFieldBinaryOpTypes op,
                                                               double lValue,
                                                               VisuScalarField *b)
{
  VisuScalarFieldBinaryOp *field;
  
  field = g_object_new(VISU_TYPE_SCALAR_FIELD_BINARY_OP,
                       "label", "binary op", NULL);
  _setOp(field, op);
  field->priv->lvalue = lValue;
  visu_scalar_field_binary_op_setRightField(field, b);

  return VISU_SCALAR_FIELD(field);
}

/**
 * visu_scalar_field_binary_op_new_withRightConst:
 * @op: the type of binary operator.
 * @a: a #VisuScalarField object.
 * @rValue: a constant.
 *
 * Like visu_scalar_field_binary_op_new() but with the right member
 * being a constant.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuScalarFieldBinaryOp
 * object.
 **/
VisuScalarField* visu_scalar_field_binary_op_new_withRightConst(VisuScalarFieldBinaryOpTypes op,
                                                                VisuScalarField *a,
                                                                double rValue)
{
  VisuScalarFieldBinaryOp *field;
  
  field = g_object_new(VISU_TYPE_SCALAR_FIELD_BINARY_OP,
                       "label", "binary op", NULL);
  _setOp(field, op);
  visu_scalar_field_binary_op_setLeftField(field, a);
  field->priv->rvalue = rValue;

  return VISU_SCALAR_FIELD(field);
}

/**
 * visu_scalar_field_binary_op_setLeftField:
 * @op: a #VisuScalarFieldBinaryOp object.
 * @field: a #VisuScalarField object.
 *
 * Change the left hand side operator to be @field.
 *
 * Returns: TRUE if the left operator is actually changed.
 **/
gboolean visu_scalar_field_binary_op_setLeftField(VisuScalarFieldBinaryOp *op,
                                                  VisuScalarField *field)
{
  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(op), FALSE);

  if (op->priv->lfield == field)
    return FALSE;

  if (op->priv->lfield)
    {
      g_signal_handler_disconnect(op->priv->lfield, op->priv->lchanged);
      g_signal_handler_disconnect(op->priv->lfield, op->priv->lempty);
      g_clear_object(&op->priv->lfield);
    }
  if (field)
    {
      op->priv->lfield = g_object_ref(field);

      visu_boxed_setBox(VISU_BOXED(op), VISU_BOXED(field));

      op->priv->lchanged = g_signal_connect_swapped(field, "changed",
                                                    G_CALLBACK(emitChanged), op);
      op->priv->lempty = g_signal_connect_swapped(field, "notify::empty",
                                                    G_CALLBACK(emitEmpty), op);
      DBG_fprintf(stderr, "Visu ScalarFieldBinaryOp: attach 'changed' signal from %p.\n", (gpointer)field);
    }
  emitChanged(op);

  return TRUE;
}

/**
 * visu_scalar_field_binary_op_setRightField:
 * @op: a #VisuScalarFieldBinaryOp object.
 * @field: a #VisuScalarField object.
 *
 * Change the right hand side operator to be @field.
 *
 * Returns: TRUE if the right operator is actually changed.
 **/
gboolean visu_scalar_field_binary_op_setRightField(VisuScalarFieldBinaryOp *op,
                                                   VisuScalarField *field)
{
  g_return_val_if_fail(VISU_IS_SCALAR_FIELD_BINARY_OP(op), FALSE);

  if (op->priv->rfield == field)
    return FALSE;

  if (op->priv->rfield)
    {
      g_signal_handler_disconnect(op->priv->rfield, op->priv->rchanged);
      g_signal_handler_disconnect(op->priv->rfield, op->priv->rempty);
      g_clear_object(&op->priv->rfield);
    }
  if (field)
    {
      op->priv->rfield = g_object_ref(field);

      visu_boxed_setBox(VISU_BOXED(op), VISU_BOXED(field));

      op->priv->rchanged = g_signal_connect_swapped(field, "changed",
                                                    G_CALLBACK(emitChanged), op);
      op->priv->rempty = g_signal_connect_swapped(field, "notify::empty",
                                                  G_CALLBACK(emitEmpty), op);
      DBG_fprintf(stderr, "Visu ScalarFieldBinaryOp: attach 'changed' signal from %p.\n", (gpointer)field);
    }
  emitChanged(op);

  return TRUE;
}
