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

#include <support.h>
#include <interface.h>

#include <visu_dataatomic.h>
#include <visu_dataspin.h>

#include <extraGtkFunctions/gtk_colorComboBoxWidget.h>
#include <extraGtkFunctions/gtk_elementComboBox.h>

#include "ui_atomic.h"
#include "ui_spin.h"

/**
 * SECTION:ui_elements
 * @short_description: Defines a widget to setup a elements.
 *
 * <para>A set of widgets to setup the rendring of a elements.</para>
 */

/**
 * VisuUiPanelElementsNewFunc:
 * @renderer: a #VisuNodeArrayRenderer object.
 *
 * Methods from this interface are called to create new interface for
 * the given node renderer.
 */
typedef GtkWidget* (*VisuUiElementsNewFunc)(VisuNodeArrayRenderer *renderer);
/**
 * VisuUiPanelElementsChangeFunc:
 * @elements: a list of all #VisuElements that are selected.
 *
 * Methods from this interface are called whenever the currently selected
 * elements are changed.
 */
typedef void (*VisuUiElementsBindFunc)(GtkWidget *widget, GList *elements);

struct _IfaceUiRendering
{
/*   setSensitiveFunc sensitiveInterface; */
  VisuUiElementsBindFunc bind;
  VisuUiElementsNewFunc createInterface;
};

/**
 * VisuUiElementsClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuUiElementsClass structure.
 *
 * Since: 3.8
 */
/**
 * VisuUiElements:
 *
 * An opaque structure.
 *
 * Since: 3.8
 */
/**
 * VisuUiElementsPrivate:
 *
 * Private fields for #VisuUiElements objects.
 *
 * Since: 3.8
 */
struct _VisuUiElementsPrivate
{
  gboolean dispose_has_run;

  GtkWidget *combo;
  GtkWidget *checkRendered;
  GtkWidget *checkMaskable;
  GtkWidget *checkColorizable;
  GtkWidget *color;

  GtkWidget *childMethod;

  GHashTable *listOfRenderingInterfaces;
  struct _IfaceUiRendering *funcs;

  VisuNodeArrayRenderer *renderer;

  VisuElementRenderer *model;
  GBinding *rendered_bind, *maskable_bind, *colorizable_bind;
  GBinding *color_bind, *material_bind;

  GList *targets;
};

static void visu_ui_elements_dispose(GObject* obj);

static void onTypeChanged(VisuNodeArrayRenderer *renderer,
                          GParamSpec *pspec, gpointer data);

G_DEFINE_TYPE_WITH_CODE(VisuUiElements, visu_ui_elements, GTK_TYPE_BOX,
                        G_ADD_PRIVATE(VisuUiElements))

static void visu_ui_elements_class_init(VisuUiElementsClass *klass)
{
  DBG_fprintf(stderr, "Ui Elements: creating the class of the widget.\n");
  DBG_fprintf(stderr, "                     - adding new signals ;\n");

  /* Connect freeing methods. */
  G_OBJECT_CLASS(klass)->dispose = visu_ui_elements_dispose;
}
static void visu_ui_elements_dispose(GObject *obj)
{
  VisuUiElements *self = VISU_UI_ELEMENTS(obj);
  DBG_fprintf(stderr, "Ui Elements: dispose object %p.\n", (gpointer)obj);

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

  visu_ui_elements_bind(self, (GList*)0);

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

static void visu_ui_elements_init(VisuUiElements *obj)
{
  GtkWidget *label, *expand, *image;
  GtkWidget *hbox;
  struct _IfaceUiRendering *wd;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new ();
#endif

  gtk_orientable_set_orientation(GTK_ORIENTABLE(obj), GTK_ORIENTATION_VERTICAL);

  obj->priv = visu_ui_elements_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  obj->priv->renderer = (VisuNodeArrayRenderer*)0;
  obj->priv->model = (VisuElementRenderer*)0;
  obj->priv->targets = (GList*)0;
  obj->priv->childMethod = (GtkWidget*)0;

  obj->priv->funcs = (struct _IfaceUiRendering*)0;

  obj->priv->listOfRenderingInterfaces = g_hash_table_new_full(g_direct_hash, g_direct_equal,
                                                               NULL, g_free);
  wd = g_malloc(sizeof(struct _IfaceUiRendering));
  wd->bind = (VisuUiElementsBindFunc)visu_ui_atomic_bind;
  wd->createInterface = visu_ui_atomic_new;
  g_hash_table_insert(obj->priv->listOfRenderingInterfaces,
                      GINT_TO_POINTER(VISU_TYPE_DATA_ATOMIC), wd);
  wd = g_malloc(sizeof(struct _IfaceUiRendering));
  wd->bind = (VisuUiElementsBindFunc)visu_ui_spin_bind;
  wd->createInterface = visu_ui_spin_new;
  g_hash_table_insert(obj->priv->listOfRenderingInterfaces,
                      GINT_TO_POINTER(VISU_TYPE_DATA_SPIN), wd);
  
  gtk_widget_set_margin_start(GTK_WIDGET(obj), 5);
  gtk_widget_set_margin_end(GTK_WIDGET(obj), 5);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(obj), hbox, FALSE, FALSE, 5);
  label = gtk_label_new(_("<b>Set caracteristics of: </b>"));
  gtk_widget_set_name(label, "label_head");
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
  /* We create the tree widget that show the methods. */
  obj->priv->combo = visu_ui_element_combobox_new(TRUE, FALSE, _("Element '%s'"));
  visu_ui_element_combobox_setUnphysicalStatus(VISU_UI_ELEMENT_COMBOBOX(obj->priv->combo), TRUE);
  g_signal_connect_swapped(obj->priv->combo, "element-selected",
                           G_CALLBACK(visu_ui_elements_bind), obj);
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->combo, TRUE, TRUE, 0);

  label = gtk_label_new("");
  gtk_label_set_markup(GTK_LABEL(label), _("<b>Standard resources</b>"));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(obj), label, FALSE, FALSE, 5);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(obj), hbox, FALSE, FALSE, 0);
/*   label = gtk_label_new(_("Color: ")); */
/*   gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2); */
  obj->priv->color = visu_ui_color_combobox_newWithRanges(TRUE);
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->color, FALSE, FALSE, 0);

  obj->priv->checkRendered = gtk_check_button_new_with_label(_("rendered"));
  gtk_widget_set_halign(obj->priv->checkRendered, GTK_ALIGN_END);
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->checkRendered, TRUE, TRUE, 2);
  
  obj->priv->checkMaskable = gtk_check_button_new();
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->checkMaskable, FALSE, FALSE, 0);
  image = create_pixmap((GtkWidget*)0, "stock-masking.png");
  gtk_container_add(GTK_CONTAINER(obj->priv->checkMaskable), image);
  gtk_widget_set_tooltip_text(obj->priv->checkMaskable,
		              _("Make nodes sensitive to a colorization effect."));

  obj->priv->checkColorizable = gtk_check_button_new_with_label(_("colorizable"));
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->checkColorizable, FALSE, FALSE, 0);
  gtk_widget_set_tooltip_text(obj->priv->checkColorizable,
		              _("Make nodes sensitive to the masking effect of planes."));
  
  expand = visu_ui_color_combobox_getRangeWidgets(VISU_UI_COLOR_COMBOBOX(obj->priv->color));
  gtk_box_pack_start(GTK_BOX(obj), expand, FALSE, FALSE, 0);

  label = gtk_label_new(_("<b>Rendering specific resources</b>"));
  gtk_widget_set_name(label, "label_head_2");
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_box_pack_start(GTK_BOX(obj), label, FALSE, FALSE, 5);
}

/**
 * visu_ui_elements_new:
 * @renderer: a #VisuNodeArrayRenderer object.
 *
 * Creates a new #VisuUiElements to allow to setup elements rendering characteristics.
 *
 * Since: 3.8
 *
 * Returns: a pointer to the newly created widget.
 */
GtkWidget* visu_ui_elements_new(VisuNodeArrayRenderer *renderer)
{
  VisuUiElements *elements;

  DBG_fprintf(stderr,"Ui Elements: new object.\n");

  elements = VISU_UI_ELEMENTS(g_object_new(VISU_TYPE_UI_ELEMENTS, NULL));
  elements->priv->renderer = renderer;
  g_object_bind_property(renderer, "data", elements->priv->combo, "nodes", G_BINDING_SYNC_CREATE);
  g_object_bind_property(renderer, "data", elements, "sensitive", G_BINDING_SYNC_CREATE);
  g_signal_connect_object(renderer, "notify::type",
                          G_CALLBACK(onTypeChanged), elements, 0);
  onTypeChanged(renderer, (GParamSpec*)0, elements);
  return GTK_WIDGET(elements);
}

static void _update(VisuUiElements *elements, GtkWidget* wd)
{
  GList *lst;

  DBG_fprintf(stderr, "Panel Element: change method specific UI.\n");
  if (elements->priv->childMethod)
    {
      /* note that gtk_destroy automatically remove
	 renderingMethodElements for its container, so
	 a call to gtk_container_remove is not necessary. */
      DBG_fprintf(stderr, "Panel Element: removing old rendering specific widget.\n");
      gtk_widget_destroy(elements->priv->childMethod);
    }
  elements->priv->childMethod = wd;
  if (wd)
    {
      gtk_box_pack_start(GTK_BOX(elements), wd, FALSE, FALSE, 5);
      gtk_box_reorder_child(GTK_BOX(elements), wd, 6);
      gtk_widget_show_all(wd);
    }

  /* Force refresh on the specific area. */
  if (elements->priv->funcs && wd)
    {
      lst = visu_ui_element_combobox_getSelection(VISU_UI_ELEMENT_COMBOBOX(elements->priv->combo));
      elements->priv->funcs->bind(wd, lst);
      g_list_free(lst);
    }
}

static void onTypeChanged(VisuNodeArrayRenderer *renderer,
                          GParamSpec *pspec _U_, gpointer data)
{
  GType type;
  struct _IfaceUiRendering *wd;
  VisuUiElements *elements = VISU_UI_ELEMENTS(data);

  g_object_get(renderer, "type", &type, NULL);
  wd = g_hash_table_lookup(elements->priv->listOfRenderingInterfaces,
                           GINT_TO_POINTER(type));

  if (wd == elements->priv->funcs)
    return;
  elements->priv->funcs = wd;

  if (wd && wd->createInterface)
    _update(elements, wd->createInterface(elements->priv->renderer));
  else
    _update(elements, (GtkWidget*)0);
}

static gboolean setForAll(GBinding *bind, const GValue *source_value,
                          GValue *target_value, gpointer data)
{
  VisuUiElements *elements = VISU_UI_ELEMENTS(data);
  GList *lst;
  
  for (lst = elements->priv->targets; lst; lst = g_list_next(lst))
    if (lst->data != elements->priv->model)
      g_object_set_property(lst->data, g_binding_get_source_property(bind), source_value);
  
  return g_value_transform(source_value, target_value);
}

static void _bind(VisuUiElements *elements, VisuElementRenderer *element)
{
  if (elements->priv->model == element)
    return;

  if (elements->priv->model)
    {
      g_object_unref(elements->priv->rendered_bind);
      g_object_unref(elements->priv->maskable_bind);
      g_object_unref(elements->priv->colorizable_bind);
      g_object_unref(elements->priv->color_bind);
      g_object_unref(elements->priv->material_bind);
      g_object_unref(elements->priv->model);
    }
  elements->priv->model = element;
  if (element)
    {
      g_object_ref(element);
      elements->priv->rendered_bind =
        g_object_bind_property_full(element, "rendered",
                                    elements->priv->checkRendered, "active",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    NULL, setForAll, elements, (GDestroyNotify)0);
      elements->priv->maskable_bind =
        g_object_bind_property_full(element, "maskable",
                                    elements->priv->checkMaskable, "active",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    NULL, setForAll, elements, (GDestroyNotify)0);
      elements->priv->colorizable_bind =
        g_object_bind_property_full(visu_element_renderer_getElement(element),
                                    "colorizable",
                                    elements->priv->checkColorizable, "active",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    NULL, setForAll, elements, (GDestroyNotify)0);
      elements->priv->color_bind =
        g_object_bind_property_full(element, "color", elements->priv->color, "color",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    NULL, setForAll, elements, (GDestroyNotify)0);
      elements->priv->material_bind =
        g_object_bind_property_full(element, "material", elements->priv->color, "material",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    NULL, setForAll, elements, (GDestroyNotify)0);
    }
}
/**
 * visu_ui_elements_bind:
 * @elements: a #VisuUiElements object.
 * @eleList: (element-type VisuElement): a list of #VisuElement.
 *
 * Use the list @eleList to be handled by @elements. Any change in
 * @elements will be applied to the #VisuElementRenderer corresponding
 * to each #VisuElement of @eleList.
 *
 * Since: 3.8
 **/
void visu_ui_elements_bind(VisuUiElements *elements, GList *eleList)
{
  GList *lst;

  g_return_if_fail(VISU_IS_UI_ELEMENTS(elements));
  g_return_if_fail(elements->priv->renderer);

  if (!eleList)
    _bind(elements, (VisuElementRenderer*)0);
  else
    {
      if (!elements->priv->model || !g_list_find(eleList, visu_element_renderer_getElement(VISU_ELEMENT_RENDERER(elements->priv->model))))
        _bind(elements, visu_node_array_renderer_get(elements->priv->renderer, VISU_ELEMENT(eleList->data)));
    }
  
  if (elements->priv->targets)
    g_list_free(elements->priv->targets);

  elements->priv->targets = (GList*)0;
  for (lst = eleList; lst; lst = g_list_next(lst))
    elements->priv->targets = g_list_prepend(elements->priv->targets, visu_node_array_renderer_get(elements->priv->renderer, VISU_ELEMENT(lst->data)));

  if (elements->priv->funcs)
    elements->priv->funcs->bind(elements->priv->childMethod, eleList);
}
