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

/**
 * SECTION:colorizer
 * @short_description: a virtual class to colorise #VisuNodeArray.
 *
 * <para></para>
 */

struct _VisuDataColorizerPrivate
{
  gboolean dispose_has_run;

  guint dirtyPending;
  gboolean active;

  VisuSourceableData *source;
};

enum {
  PROP_0,
  PROP_ACTIVE,
  N_PROPS,
  PROP_MODEL,
  PROP_SOURCE
};
static GParamSpec *_properties[N_PROPS];
enum {
  DIRTY_SIGNAL,
  LAST_SIGNAL
};
static guint _signals[LAST_SIGNAL] = { 0 };

static void visu_data_colorizer_dispose     (GObject* obj);
static void visu_data_colorizer_get_property(GObject* obj, guint property_id,
                                               GValue *value, GParamSpec *pspec);
static void visu_data_colorizer_set_property(GObject* obj, guint property_id,
                                               const GValue *value, GParamSpec *pspec);
static void visu_sourceable_interface_init(VisuSourceableInterface *iface);
static VisuSourceableData** _getSource(VisuSourceable *self);
static void _modelChanged(VisuSourceable *self);

G_DEFINE_TYPE_WITH_CODE(VisuDataColorizer, visu_data_colorizer, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuDataColorizer)
                        G_IMPLEMENT_INTERFACE(VISU_TYPE_SOURCEABLE,
                                              visu_sourceable_interface_init))

static void visu_data_colorizer_class_init(VisuDataColorizerClass *klass)
{
  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose      = visu_data_colorizer_dispose;
  G_OBJECT_CLASS(klass)->set_property = visu_data_colorizer_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_data_colorizer_get_property;

  /**
   * VisuDataColorizer::dirty:
   *
   * Gets emitted when colorizer characteristics have changed and a
   * redraw is needed.
   *
   * Since: 3.8
   */
  _signals[DIRTY_SIGNAL] =
    g_signal_new("dirty", G_TYPE_FROM_CLASS(klass),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 0 , NULL, NULL, g_cclosure_marshal_VOID__VOID,
                 G_TYPE_NONE, 0);

  /**
   * VisuDataColorizer::active:
   *
   * A flag specifying if the colorizer has changed.
   *
   * Since: 3.8
   */
  _properties[PROP_ACTIVE] =
    g_param_spec_boolean("active", "Active", "active",
                         FALSE, G_PARAM_READWRITE);

  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROPS, _properties);

  g_object_class_override_property(G_OBJECT_CLASS(klass), PROP_SOURCE, "source");
  g_object_class_override_property(G_OBJECT_CLASS(klass), PROP_MODEL, "model");
}
static void visu_sourceable_interface_init(VisuSourceableInterface *iface)
{
  iface->getSource = _getSource;
  iface->modelChanged = _modelChanged;
}
static void visu_data_colorizer_init(VisuDataColorizer *obj)
{
  DBG_fprintf(stderr, "Visu Data Colorizer: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_data_colorizer_get_instance_private(obj);

  obj->priv->dispose_has_run = FALSE;
  obj->priv->dirtyPending = 0;
  obj->priv->active = FALSE;
  visu_sourceable_init(VISU_SOURCEABLE(obj));
}
static void visu_data_colorizer_get_property(GObject* obj, guint property_id,
                                             GValue *value, GParamSpec *pspec)
{
  VisuDataColorizer *self = VISU_DATA_COLORIZER(obj);

  DBG_fprintf(stderr, "Visu Data Colorizer: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_ACTIVE:
      g_value_set_boolean(value, self->priv->active);
      DBG_fprintf(stderr, "%d.\n", self->priv->active);
      break;
    case PROP_MODEL:
      g_value_set_object(value, visu_sourceable_getNodeModel(VISU_SOURCEABLE(self)));
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(value));
      break;
    case PROP_SOURCE:
      g_value_set_string(value, visu_sourceable_getSource(VISU_SOURCEABLE(self)));
      DBG_fprintf(stderr, "%s.\n", g_value_get_string(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_set_property(GObject* obj, guint property_id,
                                             const GValue *value, GParamSpec *pspec)
{
  VisuDataColorizer *self = VISU_DATA_COLORIZER(obj);

  DBG_fprintf(stderr, "Visu Data Colorizer: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case PROP_ACTIVE:
      DBG_fprintf(stderr, "%d.\n", g_value_get_boolean(value));
      visu_data_colorizer_setActive(self, g_value_get_boolean(value));
      break;
    case PROP_MODEL:
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(value));
      visu_sourceable_setNodeModel(VISU_SOURCEABLE(obj), g_value_get_object(value));
      break;
    case PROP_SOURCE:
      DBG_fprintf(stderr, "%s.\n", g_value_get_string(value));
      visu_sourceable_setSource(VISU_SOURCEABLE(obj), g_value_get_string(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_dispose(GObject* obj)
{
  VisuDataColorizer *self;

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

  visu_sourceable_dispose(VISU_SOURCEABLE(obj));
  if (self->priv->dirtyPending)
    g_source_remove(self->priv->dirtyPending);

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

/**
 * visu_data_colorizer_getColor:
 * @colorizer: a #VisuDataColorizer object.
 * @rgba: (array fixed-size=4) (out caller-allocates): a location for
 * store a colour definition.
 * @visuData: a #VisuData object.
 * @node: a #VisuNode structure.
 *
 * Call the class colorizer function of @colorizer to setup a colour
 * in @rgba for given @node inside @visuData. If there is no specific
 * colour for this node and the default element colour should be used
 * instead, this function returns FALSE.
 *
 * Since: 3.8
 *
 * Returns: TRUE if @colorizer can actually provide a colour for @node.
 **/
gboolean visu_data_colorizer_getColor(const VisuDataColorizer *colorizer,
                                      float rgba[4], const VisuData *visuData,
                                      const VisuNode* node)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(colorizer), FALSE);

  if (!visu_data_colorizer_getActive(colorizer))
    return FALSE;
  /* if (!colorizer->priv->model) */
  /*   return FALSE; */

  if (!visu_element_getColorizable(visu_node_array_getElement(VISU_NODE_ARRAY_CONST(visuData), node)))
    return FALSE;

  if (!VISU_DATA_COLORIZER_GET_CLASS(colorizer)->colorize)
    return FALSE;

  return VISU_DATA_COLORIZER_GET_CLASS(colorizer)->colorize(colorizer, rgba,
                                                            visuData, node);
}

/**
 * visu_data_colorizer_getScalingFactor:
 * @colorizer: a #VisuDataColorizer object.
 * @visuData: a #VisuData object.
 * @node: a #VisuNode structure.
 *
 * Calls the class scaling function of @colorizer to retrieve a
 * scaling factor for @node in @visuData.
 *
 * Since: 3.8
 *
 * Returns: a scaling factor.
 **/
gfloat visu_data_colorizer_getScalingFactor(const VisuDataColorizer *colorizer,
                                            const VisuData *visuData,
                                            const VisuNode* node)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(colorizer), FALSE);

  if (!VISU_DATA_COLORIZER_GET_CLASS(colorizer)->scale)
    return 1.f;

  return VISU_DATA_COLORIZER_GET_CLASS(colorizer)->scale(colorizer, visuData, node);
}

static gboolean _emitDirty(VisuDataColorizer *colorizer)
{
  g_signal_emit(colorizer, _signals[DIRTY_SIGNAL], 0);

  colorizer->priv->dirtyPending = 0;
  return FALSE;
}
/**
 * visu_data_colorizer_setDirty:
 * @colorizer: a #VisuDataColorizer object.
 *
 * Notifies when @colorizer colorising parameters have been changed.
 *
 * Since: 3.8
 *
 * Returns: TRUE if dirty status is actually changed.
 **/
gboolean visu_data_colorizer_setDirty(VisuDataColorizer *colorizer)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(colorizer), FALSE);

  if (!colorizer->priv->active || colorizer->priv->dirtyPending)
    return FALSE;

  colorizer->priv->dirtyPending = g_idle_add((GSourceFunc)_emitDirty, colorizer);

  return TRUE;
}

/**
 * visu_data_colorizer_setActive:
 * @colorizer: a #VisuDataColorizer object.
 * @status: a boolean.
 *
 * Changes the active @status of @colorizer.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the status is actually changed.
 **/
gboolean visu_data_colorizer_setActive(VisuDataColorizer *colorizer, gboolean status)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(colorizer), FALSE);

  if (status == colorizer->priv->active)
    return FALSE;

  if (colorizer->priv->active)
    visu_data_colorizer_setDirty(colorizer);
  colorizer->priv->active = status;
  g_object_notify_by_pspec(G_OBJECT(colorizer), _properties[PROP_ACTIVE]);
  if (colorizer->priv->active)
    visu_data_colorizer_setDirty(colorizer);

  return TRUE;
}
/**
 * visu_data_colorizer_getActive:
 * @colorizer: a #VisuDataColorizer object.
 *
 * Retrieve if @colorizer is actively changing the #VisuNode colours.
 *
 * Since: 3.8
 *
 * Returns: TRUE if @colorizer is active.
 **/
gboolean visu_data_colorizer_getActive(const VisuDataColorizer *colorizer)
{
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(colorizer), FALSE);

  return colorizer->priv->active;
}

static VisuSourceableData** _getSource(VisuSourceable *self)
{
  VisuDataColorizer *colorizer = VISU_DATA_COLORIZER(self);
  
  g_return_val_if_fail(VISU_IS_DATA_COLORIZER(self), (VisuSourceableData**)0);

  return &colorizer->priv->source;
}
static void _modelChanged(VisuSourceable *self)
{
  visu_data_colorizer_setDirty(VISU_DATA_COLORIZER(self));
}
