/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	Adresse mèl :
	BILLARD, non joignable par 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 : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)

	E-mail address:
	BILLARD, not reachable any more ;
	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 "gtk_pairs.h"
#include "uiElements/ui_link.h"
#include "uiElements/ui_pairtree.h"
#include "extraGtkFunctions/gtk_curveWidget.h"
#include "extraGtkFunctions/gtk_elementComboBox.h"
#include "gtk_renderingWindowWidget.h"

#include "interface.h"
#include "support.h"
#include <string.h>
#include <stdlib.h>

#include "visu_tools.h"
#include "visu_data.h"
#include "visu_pairset.h"
#include "extensions/pairs.h"

/**
 * SECTION: gtk_pairs
 * @short_description: The pairs dialog.
 *
 * <para>The pair dialog provides a list of pairs as min/max
 * distances between species to draw pairs. A set of two species can
 * have several pairs drawn.</para>
 * <para>This dialog also hosts widgets that depend on the pair method
 * that is used for a given link.</para>
 * <para>Finally, it has also a second tab where a graph of g(r) can
 * be drawn.</para>
 */

/* static gulong unit_signal; */

static GtkWidget *uiLink, *uiTree;
static GtkWidget *curve;
static GtkWidget *spinDMin, *spinDMax, *spinDZoom;
static GtkWidget *rangeHlStart, *rangeHlEnd, *checkHighlight,
  *labelIntegralDistance, *labelMeanDistance;

/* Callbacks. */
static void _highlightRange(VisuUiCurveFrame *frame);

#define GTK_PAIRS_HELP_TEXT _("Modifications, as color or wire width, are applied only to selected rows. Use <control> to select more than one row at a time.")
#define NO_DIST_INTEGRAL _("<i>No distance analysis</i>")
#define DIST_INTEGRAL _("\342\200\242 there are %.3f neighbours per '%s'")

#define NO_DIST_MEAN ""
#define DIST_MEAN _("\342\200\242 mean distance is %.3f")

static gboolean intToText(GBinding *bind, const GValue *source_value,
                          GValue *target_value, gpointer data _U_)
{
  gchar *label;

  if (g_value_get_float(source_value) > 0.f)
    {
      g_object_get(g_binding_get_source(bind), "label", &label, NULL);
      g_value_take_string(target_value, g_strdup_printf(DIST_INTEGRAL, g_value_get_float(source_value) * 2.f, label));
      g_free(label);
    }
  else
    g_value_set_static_string(target_value, NO_DIST_INTEGRAL);
  return TRUE;
}

static gboolean meanToText(GBinding *bind _U_, const GValue *source_value,
                           GValue *target_value, gpointer data _U_)
{
  if (g_value_get_float(source_value) > 0.f)
    g_value_take_string(target_value, g_strdup_printf(DIST_MEAN, g_value_get_float(source_value)));
  else
    g_value_set_static_string(target_value, NO_DIST_MEAN);
  return TRUE;
}

void visu_ui_pairs_initBuild(VisuUiMain *main)
{
  GtkWidget *wd, *vbox, *hbox, *vbox2;
  GtkWidget *viewport;
  GtkWidget *label;

  VisuGlNodeScene *scene;
  VisuGlExtPairs *pairs;
  VisuPairSet *pairSet;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;
  tooltips = gtk_tooltips_new ();
#endif

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_getRendering(main));
  pairs = visu_gl_node_scene_getPairs(scene);
  DBG_fprintf(stderr, "Gtk Pairs: pairs has (%d) ref counts.\n", G_OBJECT(pairs)->ref_count);
  /* Create the listModel for pairs method*/
  pairSet = visu_gl_ext_pairs_getSet(pairs);

  main->pairsDialog = create_pairsDialog();
  gtk_window_set_type_hint(GTK_WINDOW(main->pairsDialog),
			   GDK_WINDOW_TYPE_HINT_UTILITY);
  gtk_window_set_default_size(GTK_WINDOW(main->pairsDialog), 100, -1);
  
  gtk_widget_set_name(main->pairsDialog, "message");

  wd = lookup_widget(main->pairsDialog, "labelTitlePairs");
  gtk_widget_set_name(wd, "message_title");

  wd = lookup_widget(main->pairsDialog, "scrolledwindowPairs");
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(wd),
				      GTK_SHADOW_ETCHED_IN);
  gtk_widget_set_size_request(wd, -1, 175);

  viewport = lookup_widget(main->pairsDialog, "viewport1");
  gtk_widget_set_name(viewport, "message_viewport");

  gtk_widget_set_name(lookup_widget(main->pairsDialog, "notebookPairs"),
		      "message_notebook");

  wd = gtk_bin_get_child(GTK_BIN(viewport));
  if (wd)
    gtk_widget_destroy(wd);

  /* Create the TreeView to represent the pairs data. */
  DBG_fprintf(stderr, "Gtk Pairs: pairs has (%d) ref counts.\n", G_OBJECT(pairs)->ref_count);
  uiTree = visu_ui_pair_tree_new(pairs);
  visu_ui_pair_tree_bind(VISU_UI_PAIR_TREE(uiTree), pairSet);
  gtk_container_add(GTK_CONTAINER(viewport), uiTree);

  wd = lookup_widget(main->pairsDialog, "hbox73");
  gtk_box_pack_start(GTK_BOX(wd), visu_ui_pair_tree_getToolbar(VISU_UI_PAIR_TREE(uiTree)),
                     FALSE, FALSE, 0);

  vbox = lookup_widget(main->pairsDialog, "vboxPairsDialog");

  uiLink = visu_ui_link_new(pairs);
  g_object_bind_property(uiTree, "selected-link", uiLink, "model",
                         G_BINDING_SYNC_CREATE);
  g_object_bind_property(scene, "data", uiLink, "data",
                         G_BINDING_SYNC_CREATE);
  g_signal_connect_swapped(G_OBJECT(uiTree), "selection-changed",
                           G_CALLBACK(visu_ui_link_setAddLinks), uiLink);
  gtk_box_pack_start(GTK_BOX(vbox), uiLink, FALSE, FALSE, 0);
  gtk_widget_show_all(uiLink);

  hbox = lookup_widget(main->pairsDialog, "hboxPairsModel");
  label = gtk_label_new("]");
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  wd = visu_ui_pair_tree_getFilter(VISU_UI_PAIR_TREE(uiTree));
  gtk_box_pack_end(GTK_BOX(hbox), wd, FALSE, FALSE, 0);

  label = gtk_label_new(_("filter: "));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  label = gtk_label_new("[");
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  gtk_widget_show_all(hbox);

  /* The "Distances" page. */
  vbox = lookup_widget(main->pairsDialog, "vboxDistances");

  curve = visu_ui_curve_frame_new(0., 5.);
  visu_ui_curve_frame_setModel(VISU_UI_CURVE_FRAME(curve), pairSet);
  g_object_bind_property(visu_ui_pair_tree_getFilter(VISU_UI_PAIR_TREE(uiTree)),
                         "element", curve, "filter", G_BINDING_SYNC_CREATE);
  gtk_widget_set_name(curve, "message_notebook");
  visu_ui_curve_frame_setStyle(VISU_UI_CURVE_FRAME(curve), CURVE_LINEAR);
  gtk_box_pack_start(GTK_BOX(vbox), curve, TRUE, TRUE, 0);

  label = gtk_label_new(_("<b>Parameters</b>:"));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
  hbox = gtk_hbox_new(FALSE, 3);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("min:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  spinDMin = gtk_spin_button_new_with_range(0., 50., 0.1);
  gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spinDMin), 2);
  g_object_bind_property(curve, "minimum", spinDMin, "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), spinDMin, FALSE, FALSE, 0);
  label = gtk_label_new(_("max:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  spinDMax = gtk_spin_button_new_with_range(0., 50., 0.1);
  gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spinDMax), 2);
  g_object_bind_property(curve, "maximum", spinDMax, "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), spinDMax, FALSE, FALSE, 0);
  label = gtk_label_new(_("step size:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  spinDZoom = gtk_spin_button_new_with_range(1., 20., 1.);
  g_object_bind_property(curve, "zoom", spinDZoom, "value", G_BINDING_SYNC_CREATE);
  gtk_box_pack_start(GTK_BOX(hbox), spinDZoom, FALSE, FALSE, 0);

  label = gtk_label_new(_("<b>Measurement tools</b>:"));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
  hbox = gtk_hbox_new(FALSE, 3);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("Range"));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 5);
  vbox2 = gtk_vbox_new(TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), vbox2, TRUE, TRUE, 0);
  rangeHlStart = gtk_hscale_new_with_range(0., 5., .05);
  g_object_bind_property(curve, "minimum",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlStart)), "lower",
                         G_BINDING_SYNC_CREATE);
  g_object_bind_property(curve, "maximum",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlStart)), "upper",
                         G_BINDING_SYNC_CREATE);
  g_object_bind_property(curve, "minimum-highlight",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlStart)), "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_scale_set_draw_value(GTK_SCALE(rangeHlStart), FALSE);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
  gtk_range_set_restrict_to_fill_level(GTK_RANGE(rangeHlStart), TRUE);
  gtk_range_set_show_fill_level(GTK_RANGE(rangeHlStart), TRUE);
#endif
  gtk_box_pack_start(GTK_BOX(vbox2), rangeHlStart, FALSE, FALSE, 0);
  rangeHlEnd = gtk_hscale_new_with_range(0., 5., .05);
  g_object_bind_property(curve, "minimum",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlEnd)), "lower",
                         G_BINDING_SYNC_CREATE);
  g_object_bind_property(curve, "maximum",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlEnd)), "upper",
                         G_BINDING_SYNC_CREATE);
  g_object_bind_property(curve, "maximum-highlight",
                         gtk_range_get_adjustment(GTK_RANGE(rangeHlEnd)), "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
  g_object_bind_property(gtk_range_get_adjustment(GTK_RANGE(rangeHlEnd)), "value",
                         rangeHlStart, "fill-level", G_BINDING_SYNC_CREATE);
#endif
  gtk_scale_set_draw_value(GTK_SCALE(rangeHlEnd), FALSE);
  gtk_box_pack_start(GTK_BOX(vbox2), rangeHlEnd, FALSE, FALSE, 0);
  vbox2 = gtk_vbox_new(TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, 0);
  checkHighlight = gtk_check_button_new_with_mnemonic(_("_Highlight nodes in range"));
  g_signal_connect_swapped(G_OBJECT(checkHighlight), "toggled",
                           G_CALLBACK(_highlightRange), curve);
  gtk_box_pack_start(GTK_BOX(vbox2), checkHighlight, FALSE, FALSE, 0);
  labelIntegralDistance = gtk_label_new(NO_DIST_INTEGRAL);
  gtk_label_set_use_markup(GTK_LABEL(labelIntegralDistance), TRUE);
  gtk_label_set_xalign(GTK_LABEL(labelIntegralDistance), 0.);
  gtk_widget_set_margin_start(labelIntegralDistance, 10);
  g_object_bind_property_full(curve, "integral-in-range", labelIntegralDistance, "label",
                              G_BINDING_SYNC_CREATE, intToText, NULL, NULL, NULL);
  gtk_box_pack_start(GTK_BOX(vbox2), labelIntegralDistance, FALSE, FALSE, 0);
  labelMeanDistance = gtk_label_new(NO_DIST_MEAN);
  gtk_label_set_use_markup(GTK_LABEL(labelMeanDistance), TRUE);
  gtk_label_set_xalign(GTK_LABEL(labelMeanDistance), 0.);
  gtk_widget_set_margin_start(labelMeanDistance, 10);
  g_object_bind_property_full(curve, "mean-in-range", labelMeanDistance, "label",
                              G_BINDING_SYNC_CREATE, meanToText, NULL, NULL, NULL);
  gtk_box_pack_start(GTK_BOX(vbox2), labelMeanDistance, FALSE, FALSE, 0);

  g_signal_connect(curve, "notify::filter",
                   G_CALLBACK(_highlightRange), (gpointer)0);
  g_signal_connect(curve, "notify::minimum-highlight",
                   G_CALLBACK(_highlightRange), (gpointer)0);
  g_signal_connect(curve, "notify::maximum-highlight",
                   G_CALLBACK(_highlightRange), (gpointer)0);

  gtk_widget_show_all(vbox);
  
  DBG_fprintf(stderr, "Gtk Pairs: Pairs are first built.\n");
}

/*************/
/* Callbacks */
/*************/
static void _highlightRange(VisuUiCurveFrame *frame)
{
  float range[2];
  GArray *ids;
  gfloat d2, xyz1[3], xyz2[3];
  VisuElement *ele;
  VisuData *dataObj;
  VisuNodeArrayIter iter1, iter2;
  VisuGlExtMarks *marks;
  VisuUiRenderingWindow *window;

  if (!visu_ui_curve_frame_getHighlightRange(frame, range))
    return;
  range[0] *= range[0];
  range[1] *= range[1];

  g_object_get(frame, "filter", &ele, NULL);

  window = visu_ui_main_class_getDefaultRendering();
  marks = visu_gl_node_scene_getMarks(visu_ui_rendering_window_getGlScene(window));
  ids = g_object_get_data(G_OBJECT(frame), "HighlightRangeIds");
  if (ids)
    {
      DBG_fprintf(stderr, "Gtk Pairs: remove %d highlights.\n", ids->len);
      visu_gl_ext_marks_setHighlight(marks, ids, MARKS_STATUS_UNSET);
      g_object_set_data(G_OBJECT(frame), "HighlightRangeIds", (gpointer)0);
    }

  if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkHighlight)))
    {
      ids = g_array_new(FALSE, FALSE, sizeof(guint));
      dataObj = visu_gl_node_scene_getData(visu_ui_rendering_window_getGlScene(window));
      visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter1);
      visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter2);
      for(visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter1),
            visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter2);
          iter1.node && iter2.node; visu_node_array_iter_next2(&iter1, &iter2))
        if (visu_element_getRendered(iter1.element) &&
            visu_element_getRendered(iter2.element) &&
            iter1.node->rendered && iter2.node->rendered &&
            (!ele || (ele && (iter1.element == ele ||
                              iter2.element == ele))))
          {
            visu_data_getNodePosition(dataObj, iter1.node, xyz1);
            visu_data_getNodePosition(dataObj, iter2.node, xyz2);
            d2 = (xyz1[0] - xyz2[0]) * (xyz1[0] - xyz2[0]) + 
              (xyz1[1] - xyz2[1]) * (xyz1[1] - xyz2[1]) + 
              (xyz1[2] - xyz2[2]) * (xyz1[2] - xyz2[2]);
            if (d2 >= range[0] && d2 < range[1])
              {
                g_array_append_val(ids, iter1.node->number);
                g_array_append_val(ids, iter2.node->number);
                /* DBG_fprintf(stderr, "Test pair %d-%d %f\n", */
                /*             iter1.node->number, iter2.node->number, d2); */
                visu_node_array_iterNext(VISU_NODE_ARRAY(dataObj), &iter1);
                visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter2);
              }
          }
      g_object_set_data_full(G_OBJECT(frame), "HighlightRangeIds",
                             ids, (GDestroyNotify)g_array_unref);
      DBG_fprintf(stderr, "Gtk Pairs: add %d highlights.\n", ids->len);
      visu_gl_ext_marks_setHighlight(marks, ids, MARKS_STATUS_SET);
    }

  if (ele)
    g_object_unref(ele);
}
