/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2016)
  
	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, (2016)

	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 "scalarFieldSet.h"

#include <string.h>

#include <visu_tools.h>

/**
 * SECTION:scalarFieldSet
 * @short_description: Defines a storage object to gather #VisuScalarField objects.
 *
 * <para>A #VisuScalarfieldSet object is a storage object for a bunch of
 * #VisuScalarField. This object provides methods to iterate over the
 * internal storage.</para>
 */

/**
 * VisuScalarfieldSetIter:
 * @set: the #VisuScalarfieldSet to iter on.
 * @field: the current #VisuScalarField.
 * @next: (element-type gpointer): internal index.
 *
 * Structure to iterate over the stored @field of @set.
 *
 * Since: 3.8
 */

struct _item
{
  gchar *label;
  VisuScalarField *field;
};

struct _item* newItem(const char *label, VisuScalarField *field)
{
  struct _item *item;

  item = g_malloc(sizeof(struct _item));
  item->label = g_strdup(label);
  g_object_ref(G_OBJECT(field));
  item->field = field;
  return item;
}
static void freeItem(struct _item *item)
{
  g_object_unref(G_OBJECT(item->field));
  g_free(item->label);
  g_free(item);
}
static gint findItem(const struct _item *a, const VisuScalarField *b)
{
  return (a->field == b) ? 0 : 1;
}

struct _VisuScalarfieldSetPrivate
{
  gboolean dispose_has_run;

  /* A GList to store all the fields. */
  GList *set;
};

enum
  {
    ADD_SIGNAL,
    REMOVE_SIGNAL,
    NB_SIGNAL
  };
static guint _signals[NB_SIGNAL] = { 0 };

enum
  {
    PROP_0,
    N_FIELDS_PROP,
    N_PROP
  };
static GParamSpec *properties[N_PROP];

static void visu_scalarfield_set_dispose     (GObject* obj);
static void visu_scalarfield_set_get_property(GObject* obj, guint property_id,
                                              GValue *value, GParamSpec *pspec);

G_DEFINE_TYPE_WITH_CODE(VisuScalarfieldSet, visu_scalarfield_set, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuScalarfieldSet))


static void visu_scalarfield_set_class_init(VisuScalarfieldSetClass *klass)
{
  DBG_fprintf(stderr, "Visu Field Set: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_scalarfield_set_dispose;
  G_OBJECT_CLASS(klass)->get_property = visu_scalarfield_set_get_property;

  /**
   * VisuScalarfieldSet::added:
   * @set: the object emitting the signal.
   * @field: the added #VisuScalarField object.
   *
   * This signal is emitted each time a field is added to
   * the set.
   *
   * Since: 3.8
   */
  _signals[ADD_SIGNAL] =
    g_signal_new("added", G_TYPE_FROM_CLASS(klass),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 0, NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
                 G_TYPE_NONE, 1, VISU_TYPE_SCALAR_FIELD, NULL);
  /**
   * VisuScalarfieldSet::removed:
   * @set: the object emitting the signal.
   * @field: the removed #VisuScalarField object.
   *
   * This signal is emitted each time a field is removed from
   * the set.
   *
   * Since: 3.8
   */
  _signals[REMOVE_SIGNAL] =
    g_signal_new("removed", G_TYPE_FROM_CLASS(klass),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 0, NULL, NULL, g_cclosure_marshal_VOID__OBJECT,
                 G_TYPE_NONE, 1, VISU_TYPE_SCALAR_FIELD, NULL);
  
  /**
   * VisuScalarfieldSet::n-fields:
   *
   * Number of stored fields.
   *
   * Since: 3.8
   */
  properties[N_FIELDS_PROP] = g_param_spec_uint("n-fields", "Number of fields",
                                                "number of fields",
                                                0, G_MAXUINT, 0, G_PARAM_READABLE |
                                                G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), N_FIELDS_PROP, properties[N_FIELDS_PROP]);
}

static void visu_scalarfield_set_init(VisuScalarfieldSet *ext)
{
  DBG_fprintf(stderr, "Visu Field Set: initializing a new object (%p).\n",
	      (gpointer)ext);
  ext->priv = visu_scalarfield_set_get_instance_private(ext);
  ext->priv->dispose_has_run = FALSE;

  ext->priv->set = (GList*)0;
}

/* This method can be called several times.
   It should unref all of its reference to
   GObjects. */
static void visu_scalarfield_set_dispose(GObject* obj)
{
  VisuScalarfieldSet *set;

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

  set = VISU_SCALARFIELD_SET(obj);
  if (set->priv->dispose_has_run)
    return;
  set->priv->dispose_has_run = TRUE;

  /* Disconnect signals. */
  g_list_free_full(set->priv->set, (GDestroyNotify)freeItem);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_scalarfield_set_parent_class)->dispose(obj);
}
static void visu_scalarfield_set_get_property(GObject* obj, guint property_id,
                                        GValue *value, GParamSpec *pspec)
{
  VisuScalarfieldSetPrivate *self = VISU_SCALARFIELD_SET(obj)->priv;

  DBG_fprintf(stderr, "Visu ScalarfieldSet: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case N_FIELDS_PROP:
      g_value_set_uint(value, g_list_length(self->set));
      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;
    }
}

/**
 * visu_scalarfield_set_new:
 *
 * Creates an object to store several fields and do hiding operations
 * with them.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): the newly created object.
 **/
VisuScalarfieldSet* visu_scalarfield_set_new()
{
  VisuScalarfieldSet *set;

  set = VISU_SCALARFIELD_SET(g_object_new(VISU_TYPE_SCALARFIELD_SET, NULL));
  return set;
}

/**
 * visu_scalarfield_set_iter_new:
 * @set: a #VisuScalarfieldSet object.
 * @iter: (out caller-allocates): the iterator to create.
 *
 * Creates an iterator on the internal storage of #VisuScalarField objects.
 *
 * Since: 3.8
 *
 * Returns: TRUE if iterator is valid (i.e. there are fields in @set).
 **/
gboolean visu_scalarfield_set_iter_new(const VisuScalarfieldSet *set, VisuScalarfieldSetIter *iter)
{
  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set) && iter, FALSE);

  memset(iter, '\0', sizeof(VisuScalarfieldSetIter));
  iter->set = set;
  iter->next = set->priv->set;
  return (iter->next != (GList*)0);
}
/**
 * visu_scalarfield_set_iter_next:
 * @iter: an iterator.
 *
 * Use this function to iterate on field stored in a #VisuScalarfieldSet object.
 *
 * Since: 3.8
 *
 * Returns: TRUE if any field remains.
 **/
gboolean visu_scalarfield_set_iter_next(VisuScalarfieldSetIter *iter)
{
  g_return_val_if_fail(iter && iter->set, FALSE);

  if (!iter->next)
    iter->field = (VisuScalarField*)0;
  else
    {
      iter->field = VISU_SCALAR_FIELD(((struct _item*)iter->next->data)->field);
      iter->next = g_list_next(iter->next);
    }
  return (iter->field != (VisuScalarField*)0);
}

/**
 * visu_scalarfield_set_getAt:
 * @set: a #VisuScalarfieldSet object.
 * @i: an index.
 *
 * Retrieve the field stored at index @i.
 *
 * Since: 3.8
 *
 * Returns: (transfer none) (allow-none): a #VisuScalarField object or NULL
 * index is out of bounds.
 **/
VisuScalarField* visu_scalarfield_set_getAt(const VisuScalarfieldSet *set, guint i)
{
  GList *at;

  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set), (VisuScalarField*)0);

  at = g_list_nth(set->priv->set, i);
  if (at)
    return VISU_SCALAR_FIELD(((struct _item*)at->data)->field);
  else
    return (VisuScalarField*)0;
}

/**
 * visu_scalarfield_set_getLabel:
 * @set: a #VisuScalarfieldSet object.
 * @field: a #VisuScalarField object.
 *
 * Retrieve the label that has been associated to @field.
 *
 * Since: 3.8
 *
 * Returns: the label associated to @field, if @field belongs to @set.
 **/
const gchar* visu_scalarfield_set_getLabel(const VisuScalarfieldSet *set,
                                           const VisuScalarField *field)
{
  GList *lst;

  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set) && field, (const gchar*)0);

  lst = g_list_find_custom(set->priv->set, field, (GCompareFunc)findItem);
  if (!lst)
    return (const gchar*)0;

  return ((struct _item*)lst->data)->label;
}

/**
 * visu_scalarfield_set_getLength:
 * @set: a #VisuScalarfieldSet object.
 *
 * Retrieve the number of fields stored in @set.
 *
 * Since: 3.8
 *
 * Returns: the size of the set.
 **/
guint visu_scalarfield_set_getLength(const VisuScalarfieldSet *set)
{
  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set), 0);

  return g_list_length(set->priv->set);
}

/**
 * visu_scalarfield_set_add:
 * @set: a #VisuScalarfieldSet object.
 * @label: a string.
 * @field: (transfer none): a #VisuScalarField object.
 *
 * Adds a @field to the list of stored fields. @label is not
 * necessarily unique in he set.
 *
 * Since: 3.8
 *
 * Returns: FALSE if @field was already registered.
 **/
gboolean visu_scalarfield_set_add(VisuScalarfieldSet *set, const gchar *label,
                                  VisuScalarField *field)
{
  GList *lst;

  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set) && field, FALSE);

  lst = g_list_find_custom(set->priv->set, field, (GCompareFunc)findItem);
  if (lst)
    return FALSE;

  set->priv->set = g_list_append(set->priv->set, newItem(label, field));
  g_signal_emit(G_OBJECT(set), _signals[ADD_SIGNAL], 0, field);
  g_object_notify_by_pspec(G_OBJECT(set), properties[N_FIELDS_PROP]);

  return TRUE;
}
static gboolean _takeFields(VisuScalarfieldSet *set,
                            const gchar *filename, GList *fields)
{
  GList *it;
  gchar *name;

  if (!fields)
    return FALSE;

  name = g_path_get_basename(filename);
  g_object_freeze_notify(G_OBJECT(set));
  for (it = fields; it; it = g_list_next(it))
    visu_scalarfield_set_add(set, name, VISU_SCALAR_FIELD(it->data));
  g_object_thaw_notify(G_OBJECT(set));
  g_free(name);

  g_list_free_full(fields, g_object_unref);

  return TRUE;
}
/**
 * visu_scalarfield_set_addFromFile:
 * @set: a #VisuScalarfieldSet object.
 * @meth: (allow-none): a #VisuScalarFieldMethod object.
 * @filename: (type filename): the path to the file to be loaded ;
 * @table: (allow-none): a set of different options (can be NULL).
 * @cancel: (allow-none): a #GCancellable object.
 * @callback: (allow-none): a method to call when the load finishes.
 * @user_data: (scope async): some user data.
 *
 * Read the given file and try to load it as a scalar field file. If succeed,
 * all read fields are added to @set. If @table is given, it means
 * that the caller routine gives some options to the loader
 * routine. These options are a set of names and values. If @meth is
 * %NULL, then all known methods are used to parse @filename.
 *
 * This is an asynchronous method. Use
 * visu_scalarfield_set_addFromFileSync() for a blocking equivalent.
 *
 * Since: 3.8
 *
 * Returns: TRUE if everything goes with no error.
 */
gboolean visu_scalarfield_set_addFromFile(VisuScalarfieldSet *set,
                                          VisuScalarFieldMethod *meth,
                                          const gchar *filename,
                                          GHashTable *table, GCancellable *cancel,
                                          GAsyncReadyCallback callback,
                                          gpointer user_data)
{
  GList *fields;

  if (meth)
    fields = visu_scalar_field_method_load(meth, filename, table, cancel,
                                           callback, user_data);
  else
    fields = visu_scalar_field_data_new_fromFile(filename, table, cancel,
                                                 callback, user_data);
  return _takeFields(set, filename, fields);
}
/**
 * visu_scalarfield_set_addFromFileSync:
 * @set: a #VisuScalarfieldSet object.
 * @meth: (allow-none): a #VisuScalarFieldMethod object.
 * @filename: (type filename): the path to the file to be loaded ;
 * @table: (allow-none): a set of different options (can be NULL).
 * @cancel: (allow-none): a #GCancellable object.
 * @error: (allow-none): an error location.
 *
 * As visu_scalarfield_set_addFromFileSync(), but blocking variant.
 *
 * Since: 3.8
 *
 * Returns: TRUE if everything goes with no error.
 */
gboolean visu_scalarfield_set_addFromFileSync(VisuScalarfieldSet *set,
                                              VisuScalarFieldMethod *meth,
                                              const gchar *filename,
                                              GHashTable *table,
                                              GCancellable *cancel,
                                              GError **error)
{
  GList *fields;

  if (meth)
    fields = visu_scalar_field_method_loadSync(meth, filename, table, cancel, error);
  else
    fields = visu_scalar_field_data_new_fromFileSync(filename, table, cancel, error);
  return _takeFields(set, filename, fields);
}
/**
 * visu_scalarfield_set_remove:
 * @set: a #VisuScalarfieldSet object.
 * @field: a #VisuScalarField object.
 *
 * Remove @field from the list of stored fields.
 *
 * Since: 3.8
 *
 * Returns: TRUE if @field was found and removed.
 **/
gboolean visu_scalarfield_set_remove(VisuScalarfieldSet *set, VisuScalarField *field)
{
  GList *lst;

  g_return_val_if_fail(VISU_IS_SCALARFIELD_SET(set) && field, FALSE);
  
  lst = g_list_find_custom(set->priv->set, field, (GCompareFunc)findItem);
  if (!lst)
    return FALSE;

  freeItem((struct _item*)lst->data);
  set->priv->set = g_list_delete_link(set->priv->set, lst);
  g_signal_emit(G_OBJECT(set), _signals[REMOVE_SIGNAL], 0, field);
  g_object_notify_by_pspec(G_OBJECT(set), properties[N_FIELDS_PROP]);

  return TRUE;
}

static VisuScalarfieldSet *defaultSet = NULL;
/**
 * visu_scalarfield_set_getDefault:
 *
 * Retrieve the default storage for #VisuScalarField objects.
 *
 * Since: 3.8
 *
 * Returns: (transfer none): the default #VisuScalarfieldSet object.
 **/
VisuScalarfieldSet* visu_scalarfield_set_getDefault(void)
{
  if (!defaultSet)
    defaultSet = visu_scalarfield_set_new();

  return defaultSet;
}
/**
 * visu_scalarfield_set_class_finalize: (skip)
 *
 * Cleanup function.
 *
 * Since: 3.8
 **/
void visu_scalarfield_set_class_finalize(void)
{
  if (defaultSet)
    g_object_unref(defaultSet);
}
