/*   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 "fragColorizer.h"

#include <coreTools/toolColor.h>

/**
 * SECTION:fragColorizer
 * @short_description: A class defining node colorisation according to
 * #VisuNodeValuesFrag.
 *
 * <para>This class implements #VisuDataColorizer for data coming from
 * #VisuNodeFragment. One can specify colorization according to
 * fragment label or fragment id, see
 * visu_data_colorizer_fragment_setType(). This class also implements
 * #VisuNodeMaskerInterface and can be used to toggle the visibility
 * of #VisuNode depending on their fragment label, see
 * visu_data_colorizer_fragment_setVisibility() and
 * visu_data_colorizer_fragment_setDefaultVisibility().</para>
 */

struct _VisuDataColorizerFragmentPrivate
{
  VisuDataColorizerFragmentTypes type;

  gboolean defaultVisibility;
  GHashTable *hidingTable;
};

enum {
  PROP_0,
  PROP_TYPE,
  N_PROPS
};
static GParamSpec *_properties[N_PROPS];

static void visu_data_colorizer_fragment_finalize(GObject* obj);
static void visu_data_colorizer_fragment_get_property(GObject* obj, guint property_id,
                                               GValue *value, GParamSpec *pspec);
static void visu_data_colorizer_fragment_set_property(GObject* obj, guint property_id,
                                               const GValue *value, GParamSpec *pspec);
static gboolean _colorize(const VisuDataColorizer *colorizer,
                          float rgba[4], const VisuData *visuData,
                          const VisuNode* node);
static void visu_node_masker_interface_init(VisuNodeMaskerInterface *iface);
static gboolean _maskApply(const VisuNodeMasker *self, VisuNodeArray *array);

G_DEFINE_TYPE_WITH_CODE(VisuDataColorizerFragment, visu_data_colorizer_fragment,
                        VISU_TYPE_DATA_COLORIZER,
                        G_ADD_PRIVATE(VisuDataColorizerFragment)
                        G_IMPLEMENT_INTERFACE(VISU_TYPE_NODE_MASKER,
                                              visu_node_masker_interface_init))

static void visu_data_colorizer_fragment_class_init(VisuDataColorizerFragmentClass *klass)
{
  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->finalize = visu_data_colorizer_fragment_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_data_colorizer_fragment_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_data_colorizer_fragment_get_property;
  VISU_DATA_COLORIZER_CLASS(klass)->colorize = _colorize;

  /**
   * VisuDataColorizerFragment::type:
   *
   * A flag specifying if the colorizer has changed.
   *
   * Since: 3.8
   */
  _properties[PROP_TYPE] =
    g_param_spec_uint("type", "Type", "colorization type",
                      0, COLORIZATION_PER_TYPE, COLORIZATION_PER_FRAGMENT, G_PARAM_READWRITE);

  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROPS, _properties);
}
static void visu_node_masker_interface_init(VisuNodeMaskerInterface *iface)
{
  iface->apply = _maskApply;
}

static void visu_data_colorizer_fragment_init(VisuDataColorizerFragment *obj)
{
  DBG_fprintf(stderr, "Visu Data Colorizer Fragment: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_data_colorizer_fragment_get_instance_private(obj);

  obj->priv->type = COLORIZATION_PER_FRAGMENT;
  obj->priv->defaultVisibility = TRUE;
  obj->priv->hidingTable = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);

  g_signal_connect(obj, "notify::active", G_CALLBACK(visu_node_masker_emitDirty),
                   (gpointer)0);
}
static void visu_data_colorizer_fragment_get_property(GObject* obj, guint property_id,
                                                      GValue *value, GParamSpec *pspec)
{
  VisuDataColorizerFragment *self = VISU_DATA_COLORIZER_FRAGMENT(obj);

  DBG_fprintf(stderr, "Visu Data Colorizer Fragment: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_TYPE:
      g_value_set_uint(value, self->priv->type);
      DBG_fprintf(stderr, "%d.\n", self->priv->type);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_data_colorizer_fragment_set_property(GObject* obj, guint property_id,
                                                      const GValue *value, GParamSpec *pspec)
{
  VisuDataColorizerFragment *self = VISU_DATA_COLORIZER_FRAGMENT(obj);

  DBG_fprintf(stderr, "Visu Data Colorizer Fragment: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_TYPE:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_data_colorizer_fragment_setType(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 void visu_data_colorizer_fragment_finalize(GObject* obj)
{
  VisuDataColorizerFragment *frag;

  g_return_if_fail(obj);

  frag = VISU_DATA_COLORIZER_FRAGMENT(obj);

  g_hash_table_destroy(frag->priv->hidingTable);

  G_OBJECT_CLASS(visu_data_colorizer_fragment_parent_class)->finalize(obj);
}

/**
 * visu_data_colorizer_fragment_new:
 *
 * Creates a #VisuDataColorizer object to colorize and hide #VisuNode
 * based on a #VisuNodeValuesFrag model.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created
 * #VisuDataColorizerFragment object.
 **/
VisuDataColorizerFragment* visu_data_colorizer_fragment_new()
{
  return VISU_DATA_COLORIZER_FRAGMENT(g_object_new(VISU_TYPE_DATA_COLORIZER_FRAGMENT, NULL));
}

/**
 * visu_data_colorizer_fragment_setNodeModel:
 * @colorizer: a #VisuDataColorizerFragment object.
 * @model: (transfer none): a #VisuNodeValuesFrag object.
 *
 * Associate @model to @colorizer.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the model is indeed changed.
 **/
gboolean visu_data_colorizer_fragment_setNodeModel(VisuDataColorizerFragment *colorizer,
                                                   VisuNodeValuesFrag *model)
{
  return visu_sourceable_setNodeModel(VISU_SOURCEABLE(colorizer),
                                      VISU_NODE_VALUES(model));
}

/**
 * visu_data_colorizer_fragment_setType:
 * @colorizer: a #VisuDataColorizerFragment object.
 * @type: a #VisuDataColorizerFragmentTypes value.
 *
 * Defines how @colorizer is changing the node colours. See
 * visu_node_array_renderer_pushColorizer() function.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the value is actually changed.
 **/
gboolean visu_data_colorizer_fragment_setType(VisuDataColorizerFragment *colorizer,
                                              VisuDataColorizerFragmentTypes type)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER_FRAGMENT(colorizer), FALSE);

  if (colorizer->priv->type == type)
    return FALSE;

  colorizer->priv->type = type;
  g_object_notify_by_pspec(G_OBJECT(colorizer), _properties[PROP_TYPE]);

  visu_data_colorizer_setDirty(VISU_DATA_COLORIZER(colorizer));

  return TRUE;
}

/**
 * visu_data_colorizer_fragment_setVisibility:
 * @frag: a #VisuDataColorizerFragment object.
 * @label: (allow-none): a string.
 * @status: a boolean.
 *
 * Change the visibility of all #VisuNode belonging to a
 * #VisuNodeFragment labelled by @label according to @status. If
 * @label is %NULL, status is changed for every fragments.
 *
 * Since: 3.8
 *
 * Returns: TRUE is the value is actually changed.
 **/
gboolean visu_data_colorizer_fragment_setVisibility(VisuDataColorizerFragment *frag,
                                                    const gchar *label,
                                                    gboolean status)
{
  gboolean old;
  VisuNodeValuesIter iter;
  VisuNodeValues *model;
  const VisuNodeFragment *f;

  g_return_val_if_fail(VISU_IS_DATA_COLORIZER_FRAGMENT(frag), FALSE);

  if (label)
    {
      old = GPOINTER_TO_INT(g_hash_table_lookup(frag->priv->hidingTable, label));
      if (old == !status)
        return FALSE;
      g_hash_table_replace(frag->priv->hidingTable, g_strdup(label),
                           GINT_TO_POINTER(!status));
    }
  else
    {
      model = visu_sourceable_getNodeModel(VISU_SOURCEABLE(frag));
      if (!model)
        return FALSE;
      for (visu_node_values_iter_new(&iter, ITER_NODES_BY_TYPE, model);
           iter.iter.node; visu_node_values_iter_next(&iter))
        {
          f = visu_node_values_frag_getAtIter(VISU_NODE_VALUES_FRAG(iter.vals), &iter);
          if (f)
            g_hash_table_replace(frag->priv->hidingTable, g_strdup(f->label),
                                 GINT_TO_POINTER(!status));
        }
    }
  if (visu_data_colorizer_getActive(VISU_DATA_COLORIZER(frag)))
    visu_node_masker_emitDirty(VISU_NODE_MASKER(frag));

  return TRUE;
}

/**
 * visu_data_colorizer_fragment_setDefaultVisibility:
 * @frag: a #VisuDataColorizerFragment object.
 * @status: a boolean.
 *
 * Defines the visibility @status of all #VisuNode not belonging to
 * any #VisuNodeFragment.
 *
 * Since: 3.8
 *
 * Returns: TRUE is the value is actually changed.
 **/
gboolean visu_data_colorizer_fragment_setDefaultVisibility(VisuDataColorizerFragment *frag,
                                                           gboolean status)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER_FRAGMENT(frag), FALSE);

  if (frag->priv->defaultVisibility == status)
    return FALSE;

  frag->priv->defaultVisibility = status;
  if (visu_data_colorizer_getActive(VISU_DATA_COLORIZER(frag)))
    visu_node_masker_emitDirty(VISU_NODE_MASKER(frag));

  return TRUE;
}

static gboolean _colorize(const VisuDataColorizer *colorizer,
                          float rgba[4], const VisuData *visuData _U_,
                          const VisuNode* node)
{
  guint id, i;
  const VisuNodeFragment *f;
  const ToolColor *color;
  const VisuNodeValues *model;

  model = visu_sourceable_getConstNodeModel(VISU_SOURCEABLE(colorizer));
  f = visu_node_values_frag_getAt(VISU_NODE_VALUES_FRAG(model), node);
  if (!f)
    return FALSE;

  switch (VISU_DATA_COLORIZER_FRAGMENT(colorizer)->priv->type)
    {
    case COLORIZATION_PER_TYPE:
      id = 0;
      for (i = 0; f->label[i]; i++)
        id += f->label[i];
      color = tool_color_new_bright(id);
      rgba[0] = color->rgba[0];
      rgba[1] = color->rgba[1];
      rgba[2] = color->rgba[2];
      rgba[3] = color->rgba[3];
      return TRUE;
    case COLORIZATION_PER_FRAGMENT:
      color = tool_color_new_bright(f->id);
      rgba[0] = color->rgba[0];
      rgba[1] = color->rgba[1];
      rgba[2] = color->rgba[2];
      rgba[3] = color->rgba[3];
      return TRUE;
    default:
      break;
    }
  
  return FALSE;
}

static gboolean _maskApply(const VisuNodeMasker *self, VisuNodeArray *array)
{
  VisuDataColorizerFragment *frag;
  gboolean redraw;
  VisuNodeValuesIter iter;
  VisuNodeValues *model;
  const VisuNodeFragment *f;

  g_return_val_if_fail(VISU_IS_DATA_COLORIZER_FRAGMENT(self), FALSE);

  frag = VISU_DATA_COLORIZER_FRAGMENT(self);

  model = visu_sourceable_getNodeModel(VISU_SOURCEABLE(self));
  if (!visu_data_colorizer_getActive(VISU_DATA_COLORIZER(self)) || !model)
    return FALSE;

  g_return_val_if_fail(visu_node_values_fromArray(model, array), FALSE);

  redraw = FALSE;
  for (visu_node_values_iter_new(&iter, ITER_NODES_VISIBLE, model);
       iter.iter.node; visu_node_values_iter_next(&iter))
    {
      f = visu_node_values_frag_getAtIter(VISU_NODE_VALUES_FRAG(iter.vals), &iter);
      if ((f && GPOINTER_TO_INT(g_hash_table_lookup(frag->priv->hidingTable, f->label)))
          || (!f && !frag->priv->defaultVisibility))
        redraw = visu_node_setVisibility(iter.iter.node, FALSE) || redraw;
    }

  return redraw;
}
