/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2016)
  
	Adresse mèl :
	BILLARD, non joignable par 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, (2016)

	E-mail address:
	BILLARD, not reachable any more ;
	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 "link.h"

#include "iface_wire.h"
#include "iface_cylinder.h"

#include <visu_basic.h>
#include <visu_configFile.h>

/**
 * SECTION:link
 * @short_description: An object to store rendering properties of a
 * #VisuPair for a given distance criterion.
 *
 * <para>#VisuPair describes pairs between two #VisuElement. Such a
 * pair can have several #VisuPairLink, depending on a distance
 * criterion. Each link then has several rendering parameters, such as
 * its color, its rendering method (wire or cylinder), if it is drawn...</para>
 */

/* Parameters */
static ToolColor *defaultPairColor = NULL;
/* static void exportConfig(GString *data, VisuData *dataObj); */

struct _VisuPairLinkPrivate
{
  gboolean dispose_has_run;

  GWeakRef ele1;
  GWeakRef ele2;

  float minMax[2];
  ToolUnits units;

  gboolean drawn;
  gboolean printLength;
  ToolColor color;

  guint width;
  ToolShade *shade;
  guint16 stipple;

  gfloat radius;
  VisuPairCylinderColorId colorType;
};

static void visu_pair_link_dispose(GObject* obj);
static void visu_pair_link_get_property(GObject* obj, guint property_id,
                                        GValue *value, GParamSpec *pspec);
static void visu_pair_link_set_property(GObject* obj, guint property_id,
                                        const GValue *value, GParamSpec *pspec);
static void visu_pair_wire_interface_init(VisuPairWireInterface *iface);
static void visu_pair_cylinder_interface_init(VisuPairCylinderInterface *iface);
static gboolean   _setWidth(VisuPairWire *data, guint val);
static guint      _getWidth(VisuPairWire *data);
static gboolean   _setShade(VisuPairWire *data, ToolShade *shade);
static ToolShade* _getShade(VisuPairWire *data);
static gboolean   _setStipple(VisuPairWire *data, guint16 stipple);
static guint16    _getStipple(VisuPairWire *data);
static gboolean   _setRadius(VisuPairCylinder *data, gfloat val);
static gfloat     _getRadius(VisuPairCylinder *data);
static gboolean   _setColorType(VisuPairCylinder *data, VisuPairCylinderColorId val);
static VisuPairCylinderColorId _getColorType(VisuPairCylinder *data);

static void onEntryUnit(VisuPairLink *link, VisuConfigFileEntry *entry, VisuConfigFile *obj);
/* enum { */
/*   LAST_SIGNAL */
/* }; */
/* static guint _signals[LAST_SIGNAL] = { 0 }; */

enum
  {
    PROP_0,
    MIN_PROP,
    MAX_PROP,
    UNITS_PROP,

    USE_PROP,
    LENGTH_PROP,
    COLOR_PROP,

    WIDTH_PROP,
    SHADE_PROP,
    STIPPLE_PROP,

    RADIUS_PROP,
    TYPE_PROP,

    N_PROP
  };
static GParamSpec *_properties[N_PROP];

G_DEFINE_TYPE_WITH_CODE(VisuPairLink, visu_pair_link, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuPairLink)
                        G_IMPLEMENT_INTERFACE(VISU_TYPE_PAIR_WIRE,
                                              visu_pair_wire_interface_init)
                        G_IMPLEMENT_INTERFACE(VISU_TYPE_PAIR_CYLINDER,
                                              visu_pair_cylinder_interface_init))

static void visu_pair_link_class_init(VisuPairLinkClass *klass)
{
  float rgbOfPairs[4] = {1.0, 0.6, 0.2, 1.};
  /* VisuConfigFileEntry *entry; */

  DBG_fprintf(stderr, "Visu Pair Link: creating the class of the object.\n");

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

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_pair_link_dispose;
  G_OBJECT_CLASS(klass)->set_property = visu_pair_link_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_pair_link_get_property;

  /**
   * VisuPairLink::min:
   *
   * Store the link minimal distance.
   *
   * Since: 3.8
   */
  _properties[MIN_PROP] = g_param_spec_float("min", "Min",
                                             "minimal distance",
                                             0.f, G_MAXFLOAT, 0.f,
                                             G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), MIN_PROP,
				  _properties[MIN_PROP]);
  /**
   * VisuPairLink::max:
   *
   * Store the link maximal distance.
   *
   * Since: 3.8
   */
  _properties[MAX_PROP] = g_param_spec_float("max", "Max",
                                             "maximal distance",
                                             0.f, G_MAXFLOAT, 0.f,
                                             G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), MAX_PROP,
				  _properties[MAX_PROP]);
  /**
   * VisuPairLink::units:
   *
   * The units of the length dimensions.
   *
   * Since: 3.8
   */
  _properties[UNITS_PROP] = g_param_spec_uint("units", "Units",
                                              "Units of dimensions",
                                              TOOL_UNITS_UNDEFINED, TOOL_UNITS_N_VALUES - 1,
                                              TOOL_UNITS_UNDEFINED, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), UNITS_PROP,
				  _properties[UNITS_PROP]);
  /**
   * VisuPairLink::drawn:
   *
   * If the link should be drawn or not.
   *
   * Since: 3.8
   */
  _properties[USE_PROP] = g_param_spec_boolean("drawn", "Drawn",
                                               "link is displayed or not",
                                               TRUE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), USE_PROP,
				  _properties[USE_PROP]);
  /**
   * VisuPairLink::display-length:
   *
   * If the link should display its length or not.
   *
   * Since: 3.8
   */
  _properties[LENGTH_PROP] = g_param_spec_boolean("display-length", "Display length",
                                                  "link displays its length or not",
                                                  FALSE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), LENGTH_PROP,
				  _properties[LENGTH_PROP]);
  /**
   * VisuPairLink::color:
   *
   * Store the color of the link.
   *
   * Since: 3.8
   */
  _properties[COLOR_PROP] = g_param_spec_boxed("color", "color", "rendering color",
                                               TOOL_TYPE_COLOR, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), COLOR_PROP, _properties[COLOR_PROP]);

  g_object_class_override_property(G_OBJECT_CLASS(klass), WIDTH_PROP, "width");
  g_object_class_override_property(G_OBJECT_CLASS(klass), STIPPLE_PROP, "stipple");
  g_object_class_override_property(G_OBJECT_CLASS(klass), SHADE_PROP, "shade");

  g_object_class_override_property(G_OBJECT_CLASS(klass), RADIUS_PROP, "radius");
  g_object_class_override_property(G_OBJECT_CLASS(klass), TYPE_PROP, "color-type");

  /* entry = visu_config_file_addEnumEntry(VISU_CONFIG_FILE_RESOURCE, */
  /*                                       FLAG_PAIRS_UNIT, DESC_PAIRS_UNIT, */
  /*                                       &defaultUnits, _toUnit, FALSE); */
  /* visu_config_file_entry_setVersion(entry, 3.8f); */
  /* visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE, */
  /*                                    exportConfig); */
  
  defaultPairColor = tool_color_addFloatRGBA(rgbOfPairs, NULL);
}
static void visu_pair_wire_interface_init(VisuPairWireInterface *iface)
{
  iface->set_width = _setWidth;
  iface->get_width = _getWidth;
  iface->set_stipple = _setStipple;
  iface->get_stipple = _getStipple;
  iface->set_shade = _setShade;
  iface->get_shade = _getShade;
}
static void visu_pair_cylinder_interface_init(VisuPairCylinderInterface *iface)
{
  iface->set_radius = _setRadius;
  iface->get_radius = _getRadius;
  iface->set_colorType = _setColorType;
  iface->get_colorType = _getColorType;
}
static void visu_pair_link_init(VisuPairLink *obj)
{
  DBG_fprintf(stderr, "Visu Pair Link: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_pair_link_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  /* Private data. */
  g_weak_ref_init(&obj->priv->ele1, (gpointer)0);
  g_weak_ref_init(&obj->priv->ele2, (gpointer)0);
  obj->priv->units             = visu_basic_getPreferedUnit();
  obj->priv->minMax[VISU_DISTANCE_MIN] = G_MAXFLOAT;
  obj->priv->minMax[VISU_DISTANCE_MAX] = G_MAXFLOAT;
  obj->priv->drawn             = TRUE;
  obj->priv->printLength       = FALSE;
  tool_color_copy(&obj->priv->color, defaultPairColor);

  obj->priv->width = G_MAXUINT;
  obj->priv->stipple = G_MAXUINT16;
  obj->priv->shade = (ToolShade*)0;

  obj->priv->radius = G_MAXFLOAT;
  obj->priv->colorType = VISU_CYLINDER_N_COLOR;

  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::main_unit",
                          G_CALLBACK(onEntryUnit), (gpointer)obj, G_CONNECT_SWAPPED);
}
static void visu_pair_link_dispose(GObject* obj)
{
  VisuPairLink *data;

  DBG_fprintf(stderr, "Visu Pair Link: dispose object %p.\n", (gpointer)obj);

  data = VISU_PAIR_LINK(obj);
  if (data->priv->dispose_has_run)
    return;
  data->priv->dispose_has_run = TRUE;

  g_weak_ref_clear(&data->priv->ele1);
  g_weak_ref_clear(&data->priv->ele2);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_pair_link_parent_class)->dispose(obj);
}
static void visu_pair_link_get_property(GObject* obj, guint property_id,
                                        GValue *value, GParamSpec *pspec)
{
  VisuPairLink *self = VISU_PAIR_LINK(obj);

  DBG_fprintf(stderr, "Visu Pair Link: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case COLOR_PROP:
      g_value_set_boxed(value, &self->priv->color);
      DBG_fprintf(stderr, "%gx%gx%g.\n", self->priv->color.rgba[0], self->priv->color.rgba[1], self->priv->color.rgba[2]);
      break;
    case MIN_PROP:
      g_value_set_float(value, self->priv->minMax[0]);
      DBG_fprintf(stderr, "%g.\n", self->priv->minMax[0]);
      break;
    case MAX_PROP:
      g_value_set_float(value, self->priv->minMax[1]);
      DBG_fprintf(stderr, "%g.\n", self->priv->minMax[1]);
      break;
    case UNITS_PROP:
      g_value_set_uint(value, self->priv->units);
      DBG_fprintf(stderr, "%d.\n", self->priv->units);
      break;
    case USE_PROP:
      g_value_set_boolean(value, self->priv->drawn);
      DBG_fprintf(stderr, "%d.\n", self->priv->drawn);
      break;
    case LENGTH_PROP:
      g_value_set_boolean(value, self->priv->printLength);
      DBG_fprintf(stderr, "%d.\n", self->priv->printLength);
      break;
    case WIDTH_PROP:
      g_value_set_uint(value, _getWidth(VISU_PAIR_WIRE(obj)));
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      break;
    case STIPPLE_PROP:
      g_value_set_uint(value, _getStipple(VISU_PAIR_WIRE(obj)));
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      break;
    case SHADE_PROP:
      g_value_set_boxed(value, self->priv->shade);
      DBG_fprintf(stderr, "%p.\n", (gpointer)self->priv->shade);
      break;
    case RADIUS_PROP:
      g_value_set_float(value, _getRadius(VISU_PAIR_CYLINDER(obj)));
      DBG_fprintf(stderr, "%g.\n", self->priv->radius);
      break;
    case TYPE_PROP:
      g_value_set_uint(value, _getColorType(VISU_PAIR_CYLINDER(obj)));
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_pair_link_set_property(GObject* obj, guint property_id,
                                        const GValue *value, GParamSpec *pspec)
{
  VisuPairLink *self = VISU_PAIR_LINK(obj);

  DBG_fprintf(stderr, "Visu Pair Link: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case COLOR_PROP:
      visu_pair_link_setColor(self, g_value_get_boxed(value));
      DBG_fprintf(stderr, "%gx%gx%g.\n", self->priv->color.rgba[0], self->priv->color.rgba[1], self->priv->color.rgba[2]);
      break;
    case MIN_PROP:
      visu_pair_link_setDistance(self, g_value_get_float(value), VISU_DISTANCE_MIN);
      DBG_fprintf(stderr, "%g.\n", self->priv->minMax[0]);
      break;
    case MAX_PROP:
      visu_pair_link_setDistance(self, g_value_get_float(value), VISU_DISTANCE_MAX);
      DBG_fprintf(stderr, "%g.\n", self->priv->minMax[1]);
      break;
    case UNITS_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_pair_link_setUnits(self, g_value_get_uint(value));
      break;
    case USE_PROP:
      visu_pair_link_setDrawn(self, g_value_get_boolean(value));
      DBG_fprintf(stderr, "%d.\n", self->priv->drawn);
      break;
    case LENGTH_PROP:
      visu_pair_link_setPrintLength(self, g_value_get_boolean(value));
      DBG_fprintf(stderr, "%d.\n", self->priv->printLength);
      break;
    case WIDTH_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_pair_wire_setWidth(VISU_PAIR_WIRE(obj), g_value_get_uint(value));
      break;
    case STIPPLE_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_pair_wire_setStipple(VISU_PAIR_WIRE(obj), (guint16)g_value_get_uint(value));
      break;
    case SHADE_PROP:
      DBG_fprintf(stderr, "%p.\n", (gpointer)g_value_get_boxed(value));
      visu_pair_wire_setShade(VISU_PAIR_WIRE(obj), (ToolShade*)g_value_dup_boxed(value));
      break;
    case RADIUS_PROP:
      DBG_fprintf(stderr, "%g.\n", g_value_get_float(value));
      visu_pair_cylinder_setRadius(VISU_PAIR_CYLINDER(obj), g_value_get_float(value));
      break;
    case TYPE_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_pair_cylinder_setColorType(VISU_PAIR_CYLINDER(obj), g_value_get_uint(value));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
/**
 * visu_pair_link_new:
 * @ele1: a #VisuElement object ;
 * @ele2: a #VisuElement object ;
 * @minMax: (array fixed-size=2): the two min and max distances.
 *
 * A link between two elements is characterized by its boundary distances.
 *
 * Returns: (transfer none): the #VisuPairLink object associated to the given two
 *          elements and distances. If none exists it is created. The
 *          returned value should not be freed.
 */
VisuPairLink* visu_pair_link_new(VisuElement *ele1, VisuElement *ele2, const float minMax[2])
{
  VisuPairLink *data;

  data = VISU_PAIR_LINK(g_object_new(VISU_TYPE_PAIR_LINK, NULL));
  data->priv->minMax[VISU_DISTANCE_MIN] = minMax[0];
  data->priv->minMax[VISU_DISTANCE_MAX] = minMax[1];
  g_weak_ref_set(&data->priv->ele1, ele1);
  g_weak_ref_set(&data->priv->ele2, ele2);
  DBG_fprintf(stderr, " | new %p %s-%s (%g %g).\n", (gpointer)data,
              ele1->name, ele2->name,
	      data->priv->minMax[0], data->priv->minMax[1]);

  return data;
}
/**
 * visu_pair_link_getFirstElement:
 * @data: a #VisuPairLink object.
 *
 * Retrieve one of the #VisuElement @data is linking.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a #VisuElement the link is linking.
 **/
VisuElement* visu_pair_link_getFirstElement(VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), (VisuElement*)0);
  return g_weak_ref_get(&data->priv->ele1);
}
/**
 * visu_pair_link_getSecondElement:
 * @data: a #VisuPairLink object.
 *
 * Retrieve one of the #VisuElement @data is linking.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a #VisuElement the link is linking.
 **/
VisuElement* visu_pair_link_getSecondElement(VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), (VisuElement*)0);
  return g_weak_ref_get(&data->priv->ele2);
}
/**
 * visu_pair_link_setDrawn:
 * @data: a #VisuPairLink object ;
 * @drawn: a boolean.
 *
 * A pair can or cannot be drawn, use this method to tune it.
 *
 * Returns: TRUE if parameter has been changed.
 */
gboolean visu_pair_link_setDrawn(VisuPairLink *data, gboolean drawn)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);

  DBG_fprintf(stderr, "Visu Pairs: set drawn status %d (%d) for %p.\n",
	      (int)drawn, (int)data->priv->drawn, (gpointer)data);
  if (data->priv->drawn == drawn)
    return FALSE;

  data->priv->drawn = drawn;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[USE_PROP]);
  return TRUE;
}
/**
 * visu_pair_link_setPrintLength:
 * @data: a #VisuPairLink object ;
 * @status: TRUE to print length near pairs.
 *
 * Set the attribute that controls if the length of pairs are drawn near pairs.
 *
 * Returns: TRUE if parameter has been changed.
 */
gboolean visu_pair_link_setPrintLength(VisuPairLink *data, gboolean status)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);

  DBG_fprintf(stderr, "Visu Pairs: set print length status %d (%d) for %p.\n",
	      (int)status, (int)data->priv->printLength, (gpointer)data);
  if (data->priv->printLength == status)
    return FALSE;

  data->priv->printLength = status;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[LENGTH_PROP]);
  return TRUE;
}
/**
 * visu_pair_link_getDrawn:
 * @data: a #VisuPairLink object ;
 *
 * A pair can or cannot be drawn, use this method to retrieve its state.
 *
 * Returns: TRUE if pairs can be drawn.
 */
gboolean visu_pair_link_getDrawn(const VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);
  return data->priv->drawn;
}
/**
 * visu_pair_link_setColor:
 * @data: a #VisuPairLink object ;
 * @destColor: a #ToolColor object.
 *
 * Set the color of the given pair.
 *
 * Returns: TRUE if parameter has been changed.
 */
gboolean visu_pair_link_setColor(VisuPairLink *data, const ToolColor* destColor)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data) && destColor, FALSE);

  DBG_fprintf(stderr, "Visu Pairs: set color [%g;%g;%g] for %p.\n",
	      destColor->rgba[0], destColor->rgba[1], destColor->rgba[2],
	      (gpointer)data);

  if (tool_color_equal(&data->priv->color, destColor))
    return FALSE;

  /* Copy values of dest to current color. */
  tool_color_copy(&data->priv->color, destColor);
  g_object_notify_by_pspec(G_OBJECT(data), _properties[COLOR_PROP]);
  return TRUE;
}
/**
 * visu_pair_link_getColor:
 * @data: a #VisuPairLink object.
 *
 * Look for the properties of the pair @data to find if a colour has
 * been defined. If none, the default colour is returned instead.
 *
 * Returns: (transfer none): a colour (don't free it).
 */
ToolColor* visu_pair_link_getColor(const VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), defaultPairColor);

  return &data->priv->color;
}
/**
 * visu_pair_link_setDistance:
 * @val: a floating point value ;
 * @data: a #VisuPairLink object ;
 * @minOrMax: #VISU_DISTANCE_MAX or #VISU_DISTANCE_MIN.
 *
 * Set the minimum or the maximum length for the given pair.
 *
 * Returns: TRUE if parameter has been changed.
 */
gboolean visu_pair_link_setDistance(VisuPairLink *data, float val,
                                    VisuPairLinkDistances minOrMax)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data) &&
                       (minOrMax == VISU_DISTANCE_MIN ||
                        minOrMax == VISU_DISTANCE_MAX), FALSE);

  if (data->priv->minMax[minOrMax] == val)
    return FALSE;

  data->priv->minMax[minOrMax] = val;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[(minOrMax) ? MAX_PROP : MIN_PROP]);
  return TRUE;
}
/**
 * visu_pair_link_setUnits:
 * @data: a #VisuPairLink object.
 * @units: a unit.
 *
 * Define the unit used to store the distances.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_pair_link_setUnits(VisuPairLink *data, ToolUnits units)
{
  ToolUnits unit_;
  double fact;

  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);

  if (data->priv->units == units)
    return FALSE;

  unit_ = data->priv->units;
  data->priv->units = units;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[UNITS_PROP]);

  if (unit_ == TOOL_UNITS_UNDEFINED || units == TOOL_UNITS_UNDEFINED)
    return TRUE;

  fact = (double)tool_physic_getUnitValueInMeter(unit_) /
    tool_physic_getUnitValueInMeter(units);

  data->priv->minMax[VISU_DISTANCE_MIN] *= fact;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[MIN_PROP]);
  data->priv->minMax[VISU_DISTANCE_MAX] *= fact;
  g_object_notify_by_pspec(G_OBJECT(data), _properties[MAX_PROP]);
  
  return TRUE;
}
/**
 * visu_pair_link_getUnits:
 * @data: a #VisuPairLink object.
 * 
 * Get the units of distance definition of @data.
 *
 * Returns: TRUE if length are printed.
 */
ToolUnits visu_pair_link_getUnits(const VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);
  return data->priv->units;
}
/**
 * visu_pair_link_getPrintLength:
 * @data: a #VisuPairLink object.
 * 
 * Get the print length parameter of a pair. This parameter is used to tell if
 * length should be drawn near pairs of this kind.
 *
 * Returns: TRUE if length are printed.
 */
gboolean visu_pair_link_getPrintLength(const VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);
  return data->priv->printLength;
}
/**
 * visu_pair_link_getDistance:
 * @data: a #VisuPairLink object ;
 * @minOrMax: #VISU_DISTANCE_MIN or #VISU_DISTANCE_MAX.
 *
 * A pair between @ele1 and @ele2 is drawn only if its length is between
 * a minimum and a maximum value. This method can get these values.
 *
 * Returns: the minimum or the maximum value for the pair between @ele1 and @ele2.
 */
float visu_pair_link_getDistance(const VisuPairLink *data, VisuPairLinkDistances minOrMax)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), 0.f);
  g_return_val_if_fail(minOrMax == VISU_DISTANCE_MIN ||
                       minOrMax == VISU_DISTANCE_MAX, 0.);

  return data->priv->minMax[minOrMax];
}
/**
 * visu_pair_link_match:
 * @data: a #VisuPairLink object.
 * @minMax: (array fixed-size=2): two floats.
 *
 * Returns if @data is a link with distance criterions defined by @minMax.
 *
 * Since: 3.8
 *
 * Returns: %TRUE, if @data matches @minMax.
 **/
gboolean visu_pair_link_match(const VisuPairLink *data, const float minMax[2])
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);
  DBG_fprintf(stderr, " | test %p (%g %g).\n", (gpointer)data,
              data->priv->minMax[0], data->priv->minMax[1]);
  return (data->priv->minMax[0] == minMax[0] && data->priv->minMax[1] == minMax[1]);
}
/**
 * visu_pair_link_isDrawn:
 * @data: a #VisuPairLink object.
 *
 * A link is used or not depending on a distance criterion and a flag,
 * see visu_pair_link_setDrawn() and visu_pair_link_setDistance().
 *
 * Since: 3.7
 *
 * Returns: TRUE if the @data is indeed drawn or not.
 **/
gboolean visu_pair_link_isDrawn(const VisuPairLink *data)
{
  g_return_val_if_fail(VISU_IS_PAIR_LINK(data), FALSE);

  return (data->priv->drawn &&
          data->priv->minMax[VISU_DISTANCE_MAX] >
          data->priv->minMax[VISU_DISTANCE_MIN] &&
          data->priv->minMax[VISU_DISTANCE_MAX] > 0.f);
}
static gboolean   _setWidth(VisuPairWire *data, guint val)
{
  if (VISU_PAIR_LINK(data)->priv->width == val)
    return FALSE;
  VISU_PAIR_LINK(data)->priv->width = val;

  return TRUE;
}
static guint      _getWidth(VisuPairWire *data)
{
  return VISU_PAIR_LINK(data)->priv->width == G_MAXUINT ? visu_pair_wire_getDefaultWidth() : VISU_PAIR_LINK(data)->priv->width;
}
static gboolean   _setShade(VisuPairWire *data, ToolShade *shade)
{
  if (tool_shade_compare(VISU_PAIR_LINK(data)->priv->shade, shade))
    return FALSE;
  VISU_PAIR_LINK(data)->priv->shade = shade;

  return TRUE;
}
static ToolShade* _getShade(VisuPairWire *data)
{
  return VISU_PAIR_LINK(data)->priv->shade;
}
static gboolean   _setStipple(VisuPairWire *data, guint16 stipple)
{
  if (VISU_PAIR_LINK(data)->priv->stipple == stipple)
    return FALSE;
  VISU_PAIR_LINK(data)->priv->stipple = stipple;

  return TRUE;
}
static guint16    _getStipple(VisuPairWire *data)
{
  return VISU_PAIR_LINK(data)->priv->stipple == G_MAXUINT16 ? visu_pair_wire_getDefaultStipple() : VISU_PAIR_LINK(data)->priv->stipple;
}
static gboolean   _setRadius(VisuPairCylinder *data, gfloat val)
{
  if (VISU_PAIR_LINK(data)->priv->radius == val)
    return FALSE;
  VISU_PAIR_LINK(data)->priv->radius = val;

  return TRUE;
}
static gfloat     _getRadius(VisuPairCylinder *data)
{
  return VISU_PAIR_LINK(data)->priv->radius == G_MAXFLOAT ? visu_pair_cylinder_getDefaultRadius() : VISU_PAIR_LINK(data)->priv->radius;
}
static gboolean   _setColorType(VisuPairCylinder *data, VisuPairCylinderColorId val)
{
  if (VISU_PAIR_LINK(data)->priv->colorType == val)
    return FALSE;
  VISU_PAIR_LINK(data)->priv->colorType = val;

  return TRUE;
}
static VisuPairCylinderColorId _getColorType(VisuPairCylinder *data)
{
  return VISU_PAIR_LINK(data)->priv->colorType >= VISU_CYLINDER_N_COLOR ? visu_pair_cylinder_getDefaultColorType() : VISU_PAIR_LINK(data)->priv->colorType;
}

static void onEntryUnit(VisuPairLink *link, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  if (link->priv->units != TOOL_UNITS_UNDEFINED)
    return;

  visu_pair_link_setUnits(link, visu_basic_getPreferedUnit());
}
/* static void exportConfig(GString *data, VisuData *dataObj _U_) */
/* { */
/*   const gchar **units; */

/*   if (defaultUnits != TOOL_UNITS_UNDEFINED) */
/*     { */
/*       units = tool_physic_getUnitNames(); */

/*       visu_config_file_exportComment(data, DESC_PAIRS_UNIT); */
/*       visu_config_file_exportEntry(data, FLAG_PAIRS_UNIT, NULL, */
/*                                    "%s", units[defaultUnits]); */
/*       visu_config_file_exportComment(data, ""); */
/*     } */
/* } */
static gboolean _next1(VisuPairLinkIter *iter, gboolean restart)
{
  if (!visu_element_getRendered(iter->iter1.element))
    return FALSE;

  if (restart)
    visu_node_array_iterRestartNode(VISU_NODE_ARRAY(iter->data), &iter->iter1);
  else
    visu_node_array_iterNextNode(VISU_NODE_ARRAY(iter->data), &iter->iter1);

  while (iter->iter1.node &&
         !visu_node_getVisibility(iter->iter1.node))
    visu_node_array_iterNextNode(VISU_NODE_ARRAY(iter->data), &iter->iter1);

  if (iter->iter1.node)
    visu_data_getNodePosition(iter->data, iter->iter1.node, iter->xyz1);
  
  return (iter->iter1.node != NULL);
}
static gboolean _next2(VisuPairLinkIter *iter, gboolean restart)
{
  if (!visu_element_getRendered(iter->iter2.element))
    return FALSE;

  if (restart)
    visu_node_array_iterRestartNode(VISU_NODE_ARRAY(iter->data), &iter->iter2);
  else
    visu_node_array_iterNextNode(VISU_NODE_ARRAY(iter->data), &iter->iter2);

  while (iter->iter2.node)
    {
      if (iter->iter1.element == iter->iter2.element &&
          iter->iter2.node >= iter->iter1.node)
        return FALSE;

      if (visu_node_getVisibility(iter->iter2.node))
        {
          visu_data_getNodePosition(iter->data, iter->iter2.node, iter->xyz2);
          iter->dxyz[0] = iter->xyz2[0] - iter->xyz1[0];
          iter->dxyz[1] = iter->xyz2[1] - iter->xyz1[1];
          iter->dxyz[2] = iter->xyz2[2] - iter->xyz1[2];
          if (iter->box)
            iter->periodic = visu_box_getInside(iter->box, iter->dxyz, 0.6f);
          iter->d2 = iter->dxyz[0] * iter->dxyz[0] +
            iter->dxyz[1] * iter->dxyz[1] +
            iter->dxyz[2] * iter->dxyz[2];
          if(iter->d2 >= iter->l2_buffered[0] && iter->d2 <= iter->l2_buffered[1])
            {
              if (iter->d2 < iter->l2[0])
                iter->coeff = (iter->d2 - iter->l2_buffered[0]) /
                  (iter->l2[0] - iter->l2_buffered[0]);
              else if (iter->d2 > iter->l2[1])
                iter->coeff = (iter->l2_buffered[1] - iter->d2) /
                  (iter->l2_buffered[1] - iter->l2[1]);
              else
                iter->coeff = 1.f;
              return TRUE;
            }
        }
      visu_node_array_iterNextNode(VISU_NODE_ARRAY(iter->data), &iter->iter2);
    }
  return FALSE;
}

/**
 * VisuPairLinkIter:
 * @parent: the #VisuPairLink this iterator is inheriting his properties.
 * @data: the #VisuData this iterator have to work on.
 * @iter1: a #VisuNodeArrayIter.
 * @iter2: a second #VisuNodeArrayIter.
 * @buffer: the length of the buffer around links, in percents.
 * @l2: the current link length, squared.
 * @l2_buffered: like @l2, but including the buffer.
 * @box: (allow-none): a given box to apply periodicity if needed.
 * @periodic: a boolean specifying if periodicity is to be taken into
 * account when computing the vector linking two nodes.
 * @xyz1: the current coordinates of the starting node in the link.
 * @xyz2: the current coordinates of the ending node in the link.
 * @dxyz: the current vector (within periodicity) linking node1 to
 * node2.
 * @d2: the length of the link, squared.
 * @coeff: a value used to characterised link length with respect to
 * buffer (1. means that length is within link characteristics, while
 * 0. means that link is outside characteristics plus buffer).
 *
 * An iterator used to generate pairs with the characteristics given
 * by @parent, over the node in @data.
 * 
 * Since: 3.8
 */

/**
 * visu_pair_link_iter_new:
 * @link: a #VisuPairLink object.
 * @data: a #VisuData object.
 * @iter: (out caller-allocates): a pointer to a #VisuPairLinkIter
 * structure.
 * @usePeriodicty: a boolean.
 *
 * Initialise a new #VisuPairLinkIter structure to iterate over links
 * defined by @link in @data. If @usePeriodicty is %TRUE, all links
 * between two nodes are kept if their smallest vector, using the
 * periodicty, is within the @link distance criterion.
 *
 * Since: 3.8
 *
 * Returns: TRUE if there is a valid link to draw.
 **/
gboolean visu_pair_link_iter_new(VisuPairLink *link, VisuData *data,
                                 VisuPairLinkIter *iter, gboolean usePeriodicty)
{
  float mM[2], length;

  g_return_val_if_fail(VISU_IS_PAIR_LINK(link) && data && iter, FALSE);

  if (!visu_pair_link_isDrawn(link))
    return FALSE;

  iter->parent = link;
  iter->data = data;
  
  visu_node_array_iter_new(VISU_NODE_ARRAY(data), &iter->iter1);
  visu_node_array_iter_new(VISU_NODE_ARRAY(data), &iter->iter2);
  iter->iter1.element = visu_pair_link_getFirstElement(link);
  iter->iter2.element = visu_pair_link_getSecondElement(link);
  g_object_unref(iter->iter2.element);
  g_object_unref(iter->iter1.element);

  iter->buffer = 0.15f;
  mM[0] = visu_pair_link_getDistance(link, VISU_DISTANCE_MIN);
  mM[1] = visu_pair_link_getDistance(link, VISU_DISTANCE_MAX);
  iter->l2[0] = mM[0] * mM[0];
  iter->l2[1] = mM[1] * mM[1];
  length = mM[1] - mM[0];
  iter->l2_buffered[0] = (mM[0] - iter->buffer * length);
  iter->l2_buffered[0] *= iter->l2_buffered[0];
  iter->l2_buffered[1] = (mM[1] + iter->buffer * length);
  iter->l2_buffered[1] *= iter->l2_buffered[1];

  iter->box = (usePeriodicty) ? visu_boxed_getBox(VISU_BOXED(data)) : (VisuBox*)0;
  iter->periodic = FALSE;

  if (_next1(iter, TRUE))
    {
      if (_next2(iter, TRUE))
        return TRUE;

      while (_next1(iter, FALSE))
        {
          if (_next2(iter, TRUE))
            return TRUE;
        };
    }

  return FALSE;
}
/**
 * visu_pair_link_iter_next:
 * @iter: a #VisuPairLinkIter object.
 *
 * Iterate to the next #VisuNode - #VisuNode pair.
 *
 * Since: 3.8
 *
 * Returns: TRUE if iterator is still valid.
 **/
gboolean visu_pair_link_iter_next(VisuPairLinkIter *iter)
{
  if (_next2(iter, FALSE))
    return TRUE;

  while (_next1(iter, FALSE))
    {
      if (_next2(iter, TRUE))
        return TRUE;
    };

  return FALSE;
}
