/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2017)
  
	Adresse 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 address:
	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 "shellProp.h"
#include "neighbours.h"

#include <visu_data.h>

/**
 * SECTION:shellProp
 * @short_description: define a #VisuNodeValues object to handle shells.
 *
 * <para>Defines a #VisuNodeValues object to store shells on every
 * nodes and get notification for them.</para>
 */

struct _VisuNodeValuesShellPrivate
{
  gboolean dispose_has_run;
  gint rootId;
  gfloat factor;
  guint level;
};

enum
  {
    PROP_0,
    ROOT_PROP,
    LEVEL_PROP,
    N_PROP
  };
static GParamSpec *_properties[N_PROP];

static gchar* _serialize(const VisuNodeValues *vals, const VisuNode *node);
static void _get_property(GObject* obj, guint property_id,
                          GValue *value, GParamSpec *pspec);
static void _set_property(GObject* obj, guint property_id,
                          const GValue *value, GParamSpec *pspec);

G_DEFINE_TYPE_WITH_CODE(VisuNodeValuesShell, visu_node_values_shell,
                        VISU_TYPE_NODE_VALUES_FRAG,
                        G_ADD_PRIVATE(VisuNodeValuesShell))

static void visu_node_values_shell_class_init(VisuNodeValuesShellClass *klass)
{
  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->set_property = _set_property;
  G_OBJECT_CLASS(klass)->get_property = _get_property;
  VISU_NODE_VALUES_CLASS(klass)->serialize = _serialize;
  
  /**
   * VisuNodeValuesShell::level:
   *
   * Level of recursion in shell building.
   *
   * Since: 3.8
   */
  _properties[LEVEL_PROP] =
    g_param_spec_uint("level", "Level",
                      "Level of recursion in shell building.",
                      2, 10, 5, G_PARAM_READWRITE);

  /**
   * VisuNodeValuesShell::root:
   *
   * Id of the root node, or -1 if not any.
   *
   * Since: 3.8
   */
  _properties[ROOT_PROP] =
    g_param_spec_int("root", "Root",
                      "Id of the root node, or -1 if not any.",
                      -1, G_MAXINT, -1, G_PARAM_READWRITE);

  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROP, _properties);
}

static void visu_node_values_shell_init(VisuNodeValuesShell *self)
{
  self->priv = visu_node_values_shell_get_instance_private(self);
  self->priv->dispose_has_run = FALSE;
  self->priv->rootId = -1;
  self->priv->factor = 0.2f;
  self->priv->level = 5;
}

static void _get_property(GObject* obj, guint property_id,
                          GValue *value, GParamSpec *pspec)
{
  VisuNodeValuesShell *self = VISU_NODE_VALUES_SHELL(obj);

  DBG_fprintf(stderr, "Visu Node Values Shell: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ROOT_PROP:
      g_value_set_int(value, self->priv->rootId);
      DBG_fprintf(stderr, "%d.\n", self->priv->rootId);
      break;
    case LEVEL_PROP:
      g_value_set_uint(value, self->priv->level);
      DBG_fprintf(stderr, "%d.\n", self->priv->level);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

static void _set_property(GObject* obj, guint property_id,
                          const GValue *value, GParamSpec *pspec)
{
  VisuNodeValuesShell *self = VISU_NODE_VALUES_SHELL(obj);

  DBG_fprintf(stderr, "Visu Node Values Shell: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ROOT_PROP:
      DBG_fprintf(stderr, "%d\n", g_value_get_int(value));
      visu_node_values_shell_compute(self, g_value_get_int(value), self->priv->factor);
      break;
    case LEVEL_PROP:
      DBG_fprintf(stderr, "%d\n", g_value_get_uint(value));
      visu_node_values_shell_setLevel(self, 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 gchar* _serialize(const VisuNodeValues *vals, const VisuNode *node)
{
  GValue value = {0, {{0}, {0}}};
  VisuNodeFragment *frag;

  if (!visu_node_values_getAt(vals, node, &value))
    return (gchar*)0;

  frag = (VisuNodeFragment*)g_value_get_boxed(&value);
  if (!frag)
    return (gchar*)0;

  return g_strdup(frag->label);
}

/**
 * visu_node_values_shell_new:
 * @arr: a #VisuNodeArray object.
 * @label: a translatable label.
 *
 * Create a new shell field.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuNodeValuesShell object.
 **/
VisuNodeValuesShell* visu_node_values_shell_new(VisuNodeArray *arr,
                                                const gchar *label)
{
  VisuNodeValuesShell *vals;

  vals = VISU_NODE_VALUES_SHELL(g_object_new(VISU_TYPE_NODE_VALUES_SHELL,
                                             "nodes", arr, "label", label,
                                             "type", VISU_TYPE_NODE_FRAGMENT,
                                             "editable", FALSE, NULL));
  return vals;
}

static gboolean _compute(VisuNodeValuesShell *shell, VisuNodeNeighbours *nei,
                         VisuNodeArray *array, guint id, guint shellId)
{
  VisuNodeNeighboursIter iter;
  const VisuNodeFragment *frag;
  VisuNodeFragment f;
  VisuNode *node;
  gboolean valid, ret;

  if (shellId > shell->priv->level)
    return TRUE;
  
  DBG_fprintf(stderr, "Visu NodeValuesShell: treating node %d (%d).\n", id, shellId);
  node = visu_node_array_getFromId(array, id);
  if (!node)
    return FALSE;

  frag = visu_node_values_frag_getAt(VISU_NODE_VALUES_FRAG(shell), node);
  if (frag && frag->id < shellId)
    return TRUE;

  if (shellId)
    f.label = g_strdup_printf(_("shell %d"), shellId);
  else
    f.label = g_strdup(_("root"));
  f.id = shellId;
  visu_node_values_frag_setAt(VISU_NODE_VALUES_FRAG(shell), node, &f);
  g_free(f.label);

  ret = TRUE;
  for (valid = visu_node_neighbours_iter(nei, &iter, id); valid;
       valid = visu_node_neighbours_iter_next(&iter))
    ret = _compute(shell, nei, array, iter.neiId, shellId + 1) && ret;
  return ret;
}

/**
 * visu_node_values_shell_compute:
 * @shell: a #VisuNodeValuesShell object.
 * @id: a node id.
 * @factor: a afctor.
 *
 * Compute the neighbouring shells of node @id. The neighbour tables
 * is computed within @factor (for the sphere radii).
 *
 * Since: 3.8
 *
 * Returns: TRUE if computation succeed.
 **/
gboolean visu_node_values_shell_compute(VisuNodeValuesShell *shell,
                                        guint id, gfloat factor)
{
  VisuNodeArray *array;
  VisuNodeNeighbours *nei;
  gboolean valid;

  g_return_val_if_fail(VISU_IS_NODE_VALUES_SHELL(shell), FALSE);
  
  if (shell->priv->rootId == (gint)id)
    return TRUE;

  array = visu_node_values_getArray(VISU_NODE_VALUES(shell));
  nei = visu_node_neighbours_new(VISU_DATA(array));
  g_object_set(nei, "factor", factor, NULL);

  visu_node_values_reset(VISU_NODE_VALUES(shell));

  shell->priv->rootId = id;
  shell->priv->factor = factor;
  valid = _compute(shell, nei, array, id, 0);
      
  g_object_unref(nei);
  g_object_unref(array);

  return valid;
}

/**
 * visu_node_values_shell_getLevel:
 * @shell: a #VisuNodeValuesShell object.
 *
 * Retrieves the current level of recursion that is done to look for
 * neighbouring shells.
 *
 * Since: 3.8
 *
 * Returns: an integer value.
 **/
guint visu_node_values_shell_getLevel(VisuNodeValuesShell *shell)
{
  g_return_val_if_fail(VISU_IS_NODE_VALUES_SHELL(shell), 5);

  return shell->priv->level;
}

/**
 * visu_node_values_shell_setLevel:
 * @shell: a #VisuNodeValuesShell object.
 * @level: an integer value.
 *
 * Defines the level of recursion that is done to look for
 * neighbouring shells.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the value is actually changed.
 **/
gboolean visu_node_values_shell_setLevel(VisuNodeValuesShell *shell, guint level)
{
  guint id;
  
  g_return_val_if_fail(VISU_IS_NODE_VALUES_SHELL(shell), FALSE);

  if (level == shell->priv->level)
    return FALSE;

  shell->priv->level = level;
  g_object_notify_by_pspec(G_OBJECT(shell), _properties[LEVEL_PROP]);

  if (shell->priv->rootId >= 0)
    {
      id = shell->priv->rootId;
      shell->priv->rootId = -1;
      visu_node_values_shell_compute(shell, id, shell->priv->factor);
    }

  return TRUE;
}

/**
 * visu_node_values_shell_getRoot:
 * @shell: a #VisuNodeValuesShell object.
 *
 * Retrieve the node id used as reference for shell computation.
 *
 * Since: 3.8
 *
 * Returns: the node id taken as reference, or -1 if none has been set.
 **/
gint visu_node_values_shell_getRoot(const VisuNodeValuesShell *shell)
{
  g_return_val_if_fail(VISU_IS_NODE_VALUES_SHELL(shell), -1);

  return shell->priv->rootId;
}
