/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD, Damien
	CALISTE, Olivier D'Astier, laboratoire L_Sim, (2001-2005)
  
	Adresses mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.
	D'ASTIER, dastier AT iie P cnam 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 and Damien
	CALISTE and Olivier D'Astier, laboratoire L_Sim, (2001-2005)

	E-mail addresses :
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.
	D'ASTIER, dastier AT iie P cnam 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 "gtkSpin.h"

#include <uiElements/ui_atomic.h>

#include <visu_gtk.h>
#include <visu_elements.h>
#include <visu_dataspin.h>
#include <renderingMethods/elementSpin.h>
#include <renderingMethods/spinMethod.h>
#include <openGLFunctions/view.h>
#include <coreTools/toolMatrix.h>
#include "gtkAtomic.h"
#include "panelElements.h"
#include "panelMethod.h"
#include <support.h>

#include <assert.h>
#include <string.h>
#include <math.h>

/**
 * SECTION:gtkSpin
 * @short_description: The gtk interface elements that can interfere
 * with renderingSpin parameters.
 *
 * <para>This is the gtk interface for all #VisuDataSpin module
 * parameters. They are split in two parts. The first part is placed
 * under the config tab and allows the user to modify the "global
 * properties" of the renderingSpin module such as cone's axe
 * orientation, and color repartition. The second part is under the
 * element panel and allows to modify each element resource. Size of
 * the arrows, and their shape can be modified.</para>
 */

#define LABEL_ARROW_SIZE      _("<i>Shape size and color properties:</i>")
#define LABEL_SPIN_POLICY     _("Drawing policy for spins with null modulus:")

static void set_view(GtkWidget* button, gpointer data);

/* A widget to select a shape for the arrows */
static GtkWidget *gtkw_cone_theta_angle = NULL;
static GtkWidget *gtkw_cone_phi_angle = NULL;
static GtkWidget *gtkw_color_wheel_angle = NULL;
static GtkWidget *gtkw_x = NULL, *gtkw_y = NULL, *gtkw_z = NULL; 
static GtkWidget *gtkw_set_view;
static GtkWidget *checkModulus, *checkAtomic;
static GtkWidget *radioPerTypeMod, *radioGlobalMod;
static GtkWidget *radioAlwaysSpin, *radioEmptySpin, *radioAtomicSpin;

static gulong x_sig, y_sig, z_sig;
static void _toSpherical(void)
{
  gfloat cart[3], sph[3];

  cart[0] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(gtkw_x));
  cart[1] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(gtkw_y));
  cart[2] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(gtkw_z));
  tool_matrix_cartesianToSpherical(sph, cart);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_cone_theta_angle),
                            sph[TOOL_MATRIX_SPHERICAL_THETA]);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_cone_phi_angle),
                            sph[TOOL_MATRIX_SPHERICAL_PHI]);
}
static void _fromSpherical(void)
{
  gfloat cart[3], sph[3];

  sph[TOOL_MATRIX_SPHERICAL_MODULUS] = 1.f;
  sph[TOOL_MATRIX_SPHERICAL_THETA] =
    gtk_spin_button_get_value(GTK_SPIN_BUTTON(gtkw_cone_theta_angle));
  sph[TOOL_MATRIX_SPHERICAL_PHI] =
    gtk_spin_button_get_value(GTK_SPIN_BUTTON(gtkw_cone_phi_angle));
  tool_matrix_sphericalToCartesian(cart, sph);
  g_signal_handler_block(gtkw_x, x_sig);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_x), cart[0]);
  g_signal_handler_unblock(gtkw_x, x_sig);
  g_signal_handler_block(gtkw_y, y_sig);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_y), cart[1]);
  g_signal_handler_unblock(gtkw_y, y_sig);
  g_signal_handler_block(gtkw_z, z_sig);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_z), cart[2]);
  g_signal_handler_unblock(gtkw_z, z_sig);
}

/* Creates the hbox containing x,y,z spin buttons */
static GtkWidget *gtk_spin_create_direction()
{
  GtkWidget *table;
  GtkWidget* label_x = gtk_label_new(_("x:"));
  GtkWidget* label_y = gtk_label_new(_("y:"));
  GtkWidget* label_z = gtk_label_new(_("z:"));
  GtkWidget* label_theta = gtk_label_new("\316\270:");
  GtkWidget* label_phi = gtk_label_new("\317\206:");
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new();
#endif

  table = gtk_grid_new();
  tool_grid_resize(tqble, 2, 6);

  gtk_label_set_xalign(GTK_LABEL(label_x), 1.);
  gtk_label_set_xalign(GTK_LABEL(label_y), 1.);
  gtk_label_set_xalign(GTK_LABEL(label_z), 1.);

  gtk_widget_set_hexpand(label_x, TRUE);
  gtk_widget_set_hexpand(label_y, TRUE);
  gtk_widget_set_hexpand(label_z, TRUE);

  gtkw_x = gtk_spin_button_new_with_range(-99.99, 99.99, 0.05);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_x), 0.);
  gtkw_y = gtk_spin_button_new_with_range(-99.99, 99.99, 0.05);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_y), 0.);
  gtkw_z = gtk_spin_button_new_with_range(-99.99, 99.99, 0.05);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_z), 1.);

  gtk_grid_attach(GTK_GRID(table), label_x, 0, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(table), label_y, 2, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(table), label_z, 4, 0, 1, 1);

  gtk_grid_attach(GTK_GRID(table), gtkw_x, 1, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(table), gtkw_y, 3, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(table), gtkw_z, 5, 0, 1, 1);

  gtk_label_set_xalign(GTK_LABEL(label_theta), 1.);
  gtk_label_set_xalign(GTK_LABEL(label_phi), 1.);

  gtk_widget_set_hexpand(label_theta, TRUE);
  gtk_widget_set_hexpand(label_phi, TRUE);

  gtkw_cone_theta_angle = gtk_spin_button_new_with_range(0, 180., 3);
  gtkw_cone_phi_angle = gtk_spin_button_new_with_range(0, 360., 3);
  gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(gtkw_cone_phi_angle), TRUE);

  gtkw_set_view = gtk_button_new_with_label(_("Set ortho."));
  gtk_widget_set_tooltip_text(gtkw_set_view,
			      _("Set the cone orientation to be orthogonal"
				" to the screen."));
  g_signal_connect(gtkw_set_view, "clicked", G_CALLBACK(set_view), NULL);

  gtk_grid_attach(GTK_GRID(table), label_theta, 0, 1, 1, 1);
  gtk_grid_attach(GTK_GRID(table), label_phi,   2, 1, 1, 1);

  gtk_grid_attach(GTK_GRID(table), gtkw_cone_theta_angle, 1, 1, 1, 1);
  gtk_grid_attach(GTK_GRID(table), gtkw_cone_phi_angle, 3, 1, 1, 1);

  gtk_grid_attach(GTK_GRID(table), gtkw_set_view, 4, 1, 2, 1);

  x_sig = g_signal_connect(gtkw_x, "value-changed",
                           G_CALLBACK(_toSpherical), (gpointer)0);
  y_sig = g_signal_connect(gtkw_y, "value-changed",
                           G_CALLBACK(_toSpherical), (gpointer)0);
  z_sig = g_signal_connect(gtkw_z, "value-changed",
                           G_CALLBACK(_toSpherical), (gpointer)0);

  g_signal_connect(gtkw_cone_theta_angle, "value-changed",
                   G_CALLBACK(_fromSpherical), (gpointer)0);
  g_signal_connect(gtkw_cone_phi_angle, "value-changed",
                   G_CALLBACK(_fromSpherical), (gpointer)0);

  return table;
}

/* Creates the hbox containing the color_wheel_angle button */
static GtkWidget *gtk_spin_create_color_wheel()
{
  GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
  GtkWidget* label = gtk_label_new(_("Rotate color wheel:"));

  gtk_label_set_xalign(GTK_LABEL(label), 0.);

  gtkw_color_wheel_angle = gtk_spin_button_new_with_range(0, 360., 3);
  gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(gtkw_color_wheel_angle), TRUE);

  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 1);
  gtk_box_pack_start(GTK_BOX(hbox), gtkw_color_wheel_angle, FALSE, FALSE, 1);

  /* Degrees. */
  label = gtk_label_new(_("deg."));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 1);

  return hbox;
}

static GtkWidget* createHidingModeRadioWidgets()
{
  GtkWidget *hbox;
  GSList *radiobutton_group;

  hbox = gtk_hbox_new(FALSE, 0);
  radioAlwaysSpin = gtk_radio_button_new_with_label(NULL, _("always"));
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(radioAlwaysSpin), (GSList*)0);
  radiobutton_group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radioAlwaysSpin));
  gtk_box_pack_start(GTK_BOX(hbox), radioAlwaysSpin, TRUE, TRUE, 1);
  radioEmptySpin = gtk_radio_button_new_with_label(NULL, _("never"));
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(radioEmptySpin), radiobutton_group);
  radiobutton_group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radioEmptySpin));
  gtk_box_pack_start(GTK_BOX(hbox), radioEmptySpin, TRUE, TRUE, 1);
  radioAtomicSpin = gtk_radio_button_new_with_label(NULL, _("atomic"));
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(radioAtomicSpin), radiobutton_group);
  radiobutton_group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radioAtomicSpin));
  gtk_box_pack_start(GTK_BOX(hbox), radioAtomicSpin, TRUE, TRUE, 1);

  return hbox;
}

static gboolean _fromModulus(GBinding *bind _U_, const GValue *source,
                             GValue *target, gpointer data _U_)
{
  g_value_set_boolean(target, g_value_get_uint(source) != VISU_METHOD_SPIN_CONSTANT);
  return TRUE;
}
static gboolean _toModulus(GBinding *bind _U_, const GValue *source,
                           GValue *target, gpointer data _U_)
{
  VisuMethodSpinModulusPolicy modPol;

  if (!g_value_get_boolean(source))
    modPol = VISU_METHOD_SPIN_CONSTANT;
  else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioPerTypeMod)))
    modPol = VISU_METHOD_SPIN_PER_TYPE;
  else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioGlobalMod)))
    modPol = VISU_METHOD_SPIN_GLOBAL;
  else
    modPol = VISU_METHOD_SPIN_CONSTANT;

  g_value_set_uint(target, modPol);

  return TRUE;
}
static gboolean _fromType(GBinding *bind _U_, const GValue *source,
                          GValue *target, gpointer data)
{
  g_value_set_boolean(target, g_value_get_uint(source) == (guint)GPOINTER_TO_INT(data));
  return TRUE;
}
static gboolean _toType(GBinding *bind _U_, const GValue *source,
                        GValue *target, gpointer data)
{
  if (!g_value_get_boolean(source))
    return FALSE;

  g_value_set_uint(target, GPOINTER_TO_INT(data));
  return TRUE;
}

static VisuMethodSpin *_spinModel = NULL;
static GBinding *useModulus_bind, *usePerType_bind, *useGlobal_bind, *useAtomic_bind;
static GBinding *useAlways_bind, *useNull_bind, *useAtom_bind;
static GBinding *spinOmega_bind, *spinTheta_bind, *spinPhi_bind;
static void _setModel(VisuMethodSpin *spin)
{
  g_return_if_fail(!spin || VISU_IS_METHOD_SPIN(spin));

  if (_spinModel)
    {
      g_object_unref(_spinModel);
      g_object_unref(useModulus_bind);
      g_object_unref(usePerType_bind);
      g_object_unref(useGlobal_bind);
      g_object_unref(useAtomic_bind);
      g_object_unref(useAlways_bind);
      g_object_unref(useNull_bind);
      g_object_unref(useAtom_bind);
      g_object_unref(spinTheta_bind);
      g_object_unref(spinPhi_bind);
      g_object_unref(spinOmega_bind);
    }
  if (spin)
    {
      g_object_ref(spin);
      useModulus_bind = g_object_bind_property_full
        (spin, "modulus-scaling", checkModulus, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromModulus, _toModulus, NULL, NULL);
      usePerType_bind = g_object_bind_property_full
        (spin, "modulus-scaling", radioPerTypeMod, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromType, _toType, GINT_TO_POINTER(VISU_METHOD_SPIN_PER_TYPE), NULL);
      useGlobal_bind = g_object_bind_property_full
        (spin, "modulus-scaling", radioGlobalMod, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromType, _toType, GINT_TO_POINTER(VISU_METHOD_SPIN_GLOBAL), NULL);
      useAtomic_bind = g_object_bind_property
        (spin, "use-atomic", checkAtomic, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      useAlways_bind = g_object_bind_property_full
        (spin, "hiding-mode", radioAlwaysSpin, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromType, _toType, GINT_TO_POINTER(VISU_METHOD_SPIN_ALWAYS), NULL);
      useNull_bind = g_object_bind_property_full
        (spin, "hiding-mode", radioEmptySpin, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromType, _toType, GINT_TO_POINTER(VISU_METHOD_SPIN_HIDE_NULL), NULL);
      useAtom_bind = g_object_bind_property_full
        (spin, "hiding-mode", radioAtomicSpin, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromType, _toType, GINT_TO_POINTER(VISU_METHOD_SPIN_ATOMIC_NULL), NULL);
      spinTheta_bind = g_object_bind_property
        (spin, "cone-theta", gtkw_cone_theta_angle, "value",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      spinPhi_bind = g_object_bind_property
        (spin, "cone-phi", gtkw_cone_phi_angle, "value",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      spinOmega_bind = g_object_bind_property
        (spin, "cone-omega", gtkw_color_wheel_angle, "value",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
    }
  _spinModel = spin;
}

/* Creates the vbox displayed in the config panel */
/**
 * visu_ui_panel_method_spin_create:
 * @scene: a #VisuGlNodeScene object.
 *
 * Creates a widget with the options for spin rendering.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly create #GtkVBox object.
 **/
GtkWidget* visu_ui_panel_method_spin_create(VisuGlNodeScene *scene _U_)
{
  GtkWidget *vbox = gtk_vbox_new(FALSE, 0);
  GtkWidget *label2 = gtk_label_new(_("Color cone orientation:"));
  GtkWidget *labelPolicy;
  GtkWidget *hbox, *label;
  GSList *radiobutton_group;

  DBG_fprintf(stderr, "Gtk Spin : building specific spin rendering method config widget.\n");

  /* Use modulus. */
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("Spin lenght is proportional to modulus: "));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 3);
  checkModulus = gtk_check_button_new();
  gtk_box_pack_start(GTK_BOX(hbox), checkModulus, FALSE, FALSE, 10);

  hbox = gtk_hbox_new(FALSE, 0);
  radioPerTypeMod = gtk_radio_button_new_with_label(NULL, _("per node type"));
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(radioPerTypeMod), (GSList*)0);
  radiobutton_group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radioPerTypeMod));
  gtk_box_pack_start(GTK_BOX(hbox), radioPerTypeMod, TRUE, TRUE, 1);
  g_object_bind_property(checkModulus, "active", radioPerTypeMod, "sensitive",
                         G_BINDING_SYNC_CREATE);
  radioGlobalMod = gtk_radio_button_new_with_label(NULL, _("globaly"));
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(radioGlobalMod), radiobutton_group);
  radiobutton_group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radioGlobalMod));
  gtk_box_pack_start(GTK_BOX(hbox), radioGlobalMod, TRUE, TRUE, 1);
  g_object_bind_property(checkModulus, "active", radioGlobalMod, "sensitive",
                         G_BINDING_SYNC_CREATE);
  gtk_widget_show_all(hbox);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

  /* Drawing atomic. */
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("Use atomic rendering in addition to spin: "));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 3);
  checkAtomic = gtk_check_button_new();
  gtk_box_pack_start(GTK_BOX(hbox), checkAtomic, FALSE, FALSE, 10);

  /* Drawing policy. */
  labelPolicy = gtk_label_new(LABEL_SPIN_POLICY);
  gtk_label_set_xalign(GTK_LABEL(labelPolicy), 0.);
  gtk_widget_set_margin_start(labelPolicy, 3);
  gtk_widget_set_name(labelPolicy, "label_head_2");
  gtk_box_pack_start(GTK_BOX(vbox), labelPolicy, FALSE, FALSE, 3);

  hbox = createHidingModeRadioWidgets();
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new("");
  gtk_label_set_markup(GTK_LABEL(label), _("Color distribution options:"));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_widget_set_margin_start(label, 5);
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 3);

  hbox = gtk_spin_create_color_wheel();
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);

  gtk_box_pack_start(GTK_BOX(vbox), label2, FALSE, FALSE, 3);
  gtk_label_set_xalign(GTK_LABEL(label2), 0.);
  hbox = gtk_spin_create_direction();
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);

  _setModel(visu_method_spin_getDefault());
  g_signal_connect_swapped(vbox, "destroy",
                           G_CALLBACK(_setModel), (gpointer)0);

  gtk_widget_show_all(vbox);

  return vbox;
}

static void set_view(GtkWidget* button _U_, gpointer data _U_)
{
  float theta;
  float phi;
  VisuGlView *view;

  view = visu_ui_panel_getView(VISU_UI_PANEL(VISU_UI_PANEL_ELEMENTS));
  if (!view)
    return;

  theta = tool_modulo_float(view->camera.theta, 360);
  if(theta > 180)
      theta = 360 - theta;
  phi = tool_modulo_float(view->camera.phi, 360);

  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_cone_theta_angle), theta);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(gtkw_cone_phi_angle), phi);
}
