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

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

#include <gtk/gtk.h>
#include <support.h>

#include <visu_object.h>
#include <visu_tools.h>
#include <gtk_pairs.h>

#include "wire.h"

#define COLOUR_DESCR_RGB 0
#define COLOUR_DESCR_HSV 1

GtkWidget *colorLengthCurve[3];
/* GtkWidget *labelCoord[3]; */
GtkWidget *labelColourDescr[3];
GtkWidget *vboxCurve[3];
GtkWidget *spinThickness;
GtkWidget *checkNonLinear;
int colorForCurve;
int colorDescr;
gulong signalSpinWidthId;

/* Callbacks */
void changeWireThickness(GtkSpinButton *spin, gpointer data);
void changeWireColorLength(GtkToggleButton *button, gpointer data);
void changeColorForCurve(GtkToggleButton *button, gpointer data);
void changeColorDescr(GtkToggleButton *button, gpointer data);
void applyChangesInCurves(GtkButton *button, gpointer data);
static void wireValuesChangedOnResources(GObject *obj, gpointer data);
/* gboolean drawCoordinates(GtkWidget *widget, GdkEvent *event, gpointer user_data); */

void setValueForColorLength();

void initGtkWireExtension(void)
{
  g_signal_connect(G_OBJECT(visu), "resourcesLoaded",
		   G_CALLBACK(wireValuesChangedOnResources), (gpointer)0);
}

GtkWidget* buildWireParameters()
{
  GtkWidget *hbox1;
  GtkWidget *vbox4;
  GtkWidget *label1;
  GtkObject *spinThickness_adj;
  GtkWidget *vbox3;
  GtkWidget *hbox4, *hbox6;
  GtkWidget *image2;
  GtkWidget *label3;
  GtkWidget *alignment2;
  GtkWidget *hbox2;
  GtkWidget *radiobuttonRGB;
  GSList *radiobuttonRGB_group = NULL;
  GtkWidget *radiobuttonHSV;
  GtkWidget *hbox5;
  GtkWidget *radiobutton1;
  GSList *radiobutton1_group = NULL;
  GtkWidget *radiobutton2;
  GtkWidget *radiobutton3;
  GtkWidget *buttonApply;
  GtkTooltips *tooltips;
  GtkWidget *frame;

  DBG_fprintf(stderr, "Gtk Wire : building interface for wire pairs.\n");

  tooltips = gtk_tooltips_new ();

  hbox1 = gtk_hbox_new (FALSE, 0);

  vbox4 = gtk_vbox_new (FALSE, 0);
  gtk_widget_show (vbox4);
  gtk_box_pack_start (GTK_BOX (hbox1), vbox4, FALSE, FALSE, 0);

  label1 = gtk_label_new (_("Thickness :"));
  gtk_widget_show (label1);
  gtk_box_pack_start (GTK_BOX (vbox4), label1, FALSE, FALSE, 0);
  gtk_misc_set_alignment (GTK_MISC (label1), 1, 0.5);

  spinThickness_adj = gtk_adjustment_new (1, 1, 50, 1, 2, 0);
  spinThickness = gtk_spin_button_new (GTK_ADJUSTMENT (spinThickness_adj), 1, 0);
  gtk_widget_show (spinThickness);
  gtk_box_pack_start (GTK_BOX (vbox4), spinThickness, FALSE, FALSE, 3);
  gtk_spin_button_set_numeric (GTK_SPIN_BUTTON (spinThickness), TRUE);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinThickness), getWireGeneralWidth());

  frame = gtk_frame_new("");
/*   gtk_widget_set_size_request(frame, -1, 75); */
  gtk_widget_show(frame);
  gtk_box_pack_start (GTK_BOX (hbox1), frame, TRUE, TRUE, 5);

  checkNonLinear = gtk_check_button_new ();
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkNonLinear), getWireNonLinear());
  gtk_widget_set_name(checkNonLinear, "message_radio");
  gtk_widget_show (checkNonLinear);

  hbox4 = gtk_hbox_new (FALSE, 2);
  gtk_widget_show (hbox4);
  gtk_container_add (GTK_CONTAINER (checkNonLinear), hbox4);

  image2 = gtk_image_new_from_stock ("gtk-select-color", GTK_ICON_SIZE_BUTTON);
  gtk_widget_show (image2);
  gtk_box_pack_start (GTK_BOX (hbox4), image2, FALSE, FALSE, 0);

  label3 = gtk_label_new_with_mnemonic (_("Color varies with length :"));
  gtk_widget_show (label3);
  gtk_box_pack_start (GTK_BOX (hbox4), label3, FALSE, FALSE, 0);

  gtk_frame_set_label_widget(GTK_FRAME(frame), checkNonLinear);


  hbox6 = gtk_hbox_new(FALSE, 0);
  gtk_widget_show(hbox6);
  gtk_container_add (GTK_CONTAINER (frame), hbox6);
  

  vbox3 = gtk_vbox_new (FALSE, 0);
  gtk_widget_show (vbox3);
  gtk_box_pack_start (GTK_BOX (hbox6), vbox3, FALSE, FALSE, 0);

  alignment2 = gtk_alignment_new (1, 0.5, 0, 0);
  gtk_widget_show (alignment2);
  gtk_box_pack_start (GTK_BOX (vbox3), alignment2, FALSE, FALSE, 0);

  hbox2 = gtk_hbox_new (FALSE, 0);
  gtk_widget_show (hbox2);
  gtk_container_add (GTK_CONTAINER (alignment2), hbox2);

  radiobuttonRGB = gtk_radio_button_new_with_mnemonic (NULL, _("RGB"));
  gtk_widget_set_name(radiobuttonRGB, "message_radio");
  gtk_widget_show (radiobuttonRGB);
  gtk_box_pack_start (GTK_BOX (hbox2), radiobuttonRGB, FALSE, FALSE, 0);
  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radiobuttonRGB), radiobuttonRGB_group);
  radiobuttonRGB_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobuttonRGB));
  colorDescr = 0;

  radiobuttonHSV = gtk_radio_button_new_with_mnemonic (NULL, _("HSV"));
  gtk_widget_set_name(radiobuttonHSV, "message_radio");
  gtk_widget_show (radiobuttonHSV);
  gtk_box_pack_start (GTK_BOX (hbox2), radiobuttonHSV, FALSE, FALSE, 0);
  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radiobuttonHSV), radiobuttonRGB_group);
  radiobuttonRGB_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobuttonHSV));

  hbox5 = gtk_hbox_new (FALSE, 0);
  gtk_widget_show (hbox5);
  gtk_box_pack_start (GTK_BOX (vbox3), hbox5, FALSE, FALSE, 0);

/*   radiobutton1 = gtk_radio_button_new_with_mnemonic (NULL, _("R")); */
  radiobutton1 = gtk_radio_button_new(NULL);
  gtk_widget_set_name(radiobutton1, "message_radio");
  gtk_widget_show (radiobutton1);
  gtk_box_pack_start (GTK_BOX (hbox5), radiobutton1, FALSE, FALSE, 0);
  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radiobutton1), radiobutton1_group);
  radiobutton1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton1));
  labelColourDescr[0] = gtk_label_new("R");
  gtk_widget_show(labelColourDescr[0]);
  gtk_container_add(GTK_CONTAINER(radiobutton1), labelColourDescr[0]);

/*   radiobutton2 = gtk_radio_button_new_with_mnemonic (NULL, _("G")); */
  radiobutton2 = gtk_radio_button_new(NULL);
  gtk_widget_set_name(radiobutton2, "message_radio");
  gtk_widget_show (radiobutton2);
  gtk_box_pack_start (GTK_BOX (hbox5), radiobutton2, FALSE, FALSE, 0);
  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radiobutton2), radiobutton1_group);
  radiobutton1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton2));
  labelColourDescr[1] = gtk_label_new("G");
  gtk_widget_show(labelColourDescr[1]);
  gtk_container_add(GTK_CONTAINER(radiobutton2), labelColourDescr[1]);

/*   radiobutton3 = gtk_radio_button_new_with_mnemonic (NULL, _("B")); */
  radiobutton3 = gtk_radio_button_new(NULL);
  gtk_widget_set_name(radiobutton3, "message_radio");
  gtk_widget_show (radiobutton3);
  gtk_box_pack_start (GTK_BOX (hbox5), radiobutton3, FALSE, FALSE, 0);
  gtk_radio_button_set_group (GTK_RADIO_BUTTON (radiobutton3), radiobutton1_group);
  radiobutton1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton3));
  labelColourDescr[2] = gtk_label_new("B");
  gtk_widget_show(labelColourDescr[2]);
  gtk_container_add(GTK_CONTAINER(radiobutton3), labelColourDescr[2]);

  buttonApply = gtk_button_new_from_stock ("gtk-apply");
  gtk_widget_show (buttonApply);
  gtk_box_pack_start (GTK_BOX (hbox5), buttonApply, TRUE, FALSE, 0);
  gtk_tooltips_set_tip (tooltips, buttonApply, _("Click here to aply all changes done to the curves."), NULL);

  /* Curve + label */
  vboxCurve[0] = gtk_vbox_new (FALSE, 0);
  gtk_widget_show (vboxCurve[0]);
  gtk_box_pack_start (GTK_BOX (hbox6), vboxCurve[0], TRUE, TRUE, 0);
  colorLengthCurve[0] = gtk_curve_new ();
  gtk_widget_show (colorLengthCurve[0]);
  gtk_box_pack_start (GTK_BOX (vboxCurve[0]), colorLengthCurve[0], TRUE, TRUE, 0);
  gtk_curve_set_range (GTK_CURVE (colorLengthCurve[0]), 0, 1, 0, 1);
/*   labelCoord[0] = gtk_label_new (_("0.1")); */
/*   gtk_widget_show (labelCoord[0]); */
/*   gtk_box_pack_start (GTK_BOX (vboxCurve[0]), labelCoord[0], FALSE, FALSE, 0); */

  vboxCurve[1] = gtk_vbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (hbox6), vboxCurve[1], TRUE, TRUE, 0);
  colorLengthCurve[1] = gtk_curve_new ();
  gtk_widget_show (colorLengthCurve[1]);
  gtk_box_pack_start (GTK_BOX (vboxCurve[1]), colorLengthCurve[1], TRUE, TRUE, 0);
  gtk_curve_set_range (GTK_CURVE (colorLengthCurve[1]), 0, 1, 0, 1);
/*   labelCoord[1] = gtk_label_new (_("0.2")); */
/*   gtk_widget_show (labelCoord[1]); */
/*   gtk_box_pack_start (GTK_BOX (vboxCurve[1]), labelCoord[1], FALSE, FALSE, 0); */

  vboxCurve[2] = gtk_vbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (hbox6), vboxCurve[2], TRUE, TRUE, 0);
  colorLengthCurve[2] = gtk_curve_new ();
  gtk_widget_show (colorLengthCurve[2]);
  gtk_box_pack_start (GTK_BOX (vboxCurve[2]), colorLengthCurve[2], TRUE, TRUE, 0);
  gtk_curve_set_range (GTK_CURVE (colorLengthCurve[2]), 0, 1, 0, 1);
/*   labelCoord[2] = gtk_label_new (_("0.3")); */
/*   gtk_widget_show (labelCoord[2]); */
/*   gtk_box_pack_start (GTK_BOX (vboxCurve[2]), labelCoord[2], FALSE, FALSE, 0); */

  setValueForColorLength();


  signalSpinWidthId = g_signal_connect(G_OBJECT(spinThickness), "value-changed",
				       G_CALLBACK(changeWireThickness), (gpointer)0);

  g_signal_connect(G_OBJECT(checkNonLinear), "toggled",
		   G_CALLBACK(changeWireColorLength), (gpointer)0);

  g_signal_connect(G_OBJECT(buttonApply), "clicked",
		   G_CALLBACK(applyChangesInCurves), (gpointer)0);

  g_signal_connect(G_OBJECT(radiobutton1), "toggled",
		   G_CALLBACK(changeColorForCurve), GINT_TO_POINTER(0));
  g_signal_connect(G_OBJECT(radiobutton2), "toggled",
		   G_CALLBACK(changeColorForCurve), GINT_TO_POINTER(1));
  g_signal_connect(G_OBJECT(radiobutton3), "toggled",
		   G_CALLBACK(changeColorForCurve), GINT_TO_POINTER(2));

  g_signal_connect(G_OBJECT(radiobuttonRGB), "toggled",
		   G_CALLBACK(changeColorDescr), GINT_TO_POINTER(COLOUR_DESCR_RGB));
  g_signal_connect(G_OBJECT(radiobuttonHSV), "toggled",
		   G_CALLBACK(changeColorDescr), GINT_TO_POINTER(COLOUR_DESCR_HSV));
/*   g_signal_connect(G_OBJECT(colorLengthCurve[0]), "event", */
/* 		   G_CALLBACK(drawCoordinates), GINT_TO_POINTER(0)); */

  return hbox1;
}

gchar* buildWireLabels(PairsData *data)
{
  GString *str;
  int *width;
  int val;

  width = (int*)getPairsProperty(data, "width");
  if (width)
    val = *width;
  else
    val = getWireGeneralWidth();
      
  str = g_string_new("");
  g_string_printf(str, _("%2dpx"), val);

  return g_string_free(str, FALSE);
}

void signalWireSelected(PairsData *data)
{
  int *width;
  int val;

  width = (int*)getPairsProperty(data, "width");
  if (width)
    val = *width;
  else
    val = getWireGeneralWidth();

  g_signal_handler_block(G_OBJECT(spinThickness), signalSpinWidthId);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinThickness), val);
  g_signal_handler_unblock(G_OBJECT(spinThickness), signalSpinWidthId);
}

int changeWidthValue(PairsData *data, gpointer userData)
{
  return setWireWidth(data, (int)gtk_spin_button_get_value(GTK_SPIN_BUTTON(userData)));
}


void changeWireThickness(GtkSpinButton *spin, gpointer data)
{
  int res;

  res = gtkPairsSet_specificLabels(buildWireLabels, changeWidthValue, (gpointer)spin);
  if (res)
    gtkPairs_createPairs();
}

void applyChangesInCurves(GtkButton *button, gpointer data)
{
  if (getWireNonLinear())
    {
      DBG_fprintf(stderr, "Gtk Wire : apply changes in curves.\n");
      setValueForColorLength();
      gtkPairs_createPairs();
    }
}

void changeWireColorLength(GtkToggleButton *button, gpointer data)
{
  int res;
  gboolean checked;

  checked = gtk_toggle_button_get_active(button);
  res = setWireNonLinear((int)checked);
  if (res)
    gtkPairs_createPairs();
}

void changeColorForCurve(GtkToggleButton *button, gpointer data)
{
  int color;

  if (!gtk_toggle_button_get_active(button))
    return;
  
  color = GPOINTER_TO_INT(data);
  if ( color < 0 || color > 2)
    {
      fprintf(stderr, "WARNING! Wrong parameters in call of changeColorForCurve.\n");
      return;
    }

  gtk_widget_hide(vboxCurve[colorForCurve]);
  gtk_widget_show(vboxCurve[color]);
  colorForCurve = color;
}

void setValueForColorLength()
{
  gfloat *values[3], *tmp[3];
  int nb[3];
  int color;
  int i;
  gfloat var_h, var_i, var_0, var_1, var_2, var_3;

  setPairsAreOutOfDate();
  if (colorDescr == 0)
    {
      DBG_fprintf(stderr, "Gtk Wire : set color with RGB description.\n");
      for ( color = 0; color < 3; color++)
	{
	  nb[color] = 0;
	  values[color] = (gfloat*)getLengthSampleForColor(color, nb + color);
	  if (!values[color] || nb[color] <= 0)
	    return;
	  gtk_curve_get_vector(GTK_CURVE(colorLengthCurve[color]), nb[color], values[color]);
	}
    }
  else
    {
      DBG_fprintf(stderr, "Gtk Wire : set color with HSV description.\n");
      for ( color = 0; color < 3; color++)
	{
	  nb[color] = 0;
	  values[color] = (gfloat*)getLengthSampleForColor(color, nb + color);
	  if (!values[color] || nb[color] <= 0)
	    break;
	  tmp[color] = (gfloat*)0;
	  tmp[color] = malloc(sizeof(gfloat) * nb[color]);
	  if (!tmp[color])
	    {
	      allocationProblems();
	      exit(1);
	    }
	  gtk_curve_get_vector(GTK_CURVE(colorLengthCurve[color]), nb[color], tmp[color]);
	}
      if (nb[0] != nb[1] || nb[1] != nb[2] || nb[2] != nb[0])
	g_warning("INTERNAL ERROR! Vectors to store color changes"
		  " are not of the same size for R, G and B values.\n");
      else
	{
	  for (i = 0; i < nb[0]; i++)
	    {
	      /* Transform HSV (ie. tmp[0], tmp[1], tmp[2]) to RGB values. */
	      if (tmp[1][i] == 0)
		{
		  values[0][i] = tmp[2][i];
		  values[1][i] = tmp[2][i];
		  values[2][i] = tmp[2][i];
		}
	      else
		{
		  var_h = tmp[0][i] * 6.;
		  var_i = (int)var_h;
		  var_0 = tmp[2][i];
		  var_1 = tmp[2][i] * (1. - tmp[1][i]);
		  var_2 = tmp[2][i] * (1. - tmp[1][i] * (var_h - var_i));
		  var_3 = tmp[2][i] * (1. - tmp[1][i] * (1. - (var_h - var_i)));
		  switch ((int)var_i)
		    {
		    case 0:
		      values[0][i] = var_0;
		      values[1][i] = var_3;
		      values[2][i] = var_1;
		      break;
		    case 1:
		      values[0][i] = var_2;
		      values[1][i] = var_0;
		      values[2][i] = var_1;
		      break;
		    case 2:
		      values[0][i] = var_1;
		      values[1][i] = var_0;
		      values[2][i] = var_3;
		      break;
		    case 3:
		      values[0][i] = var_1;
		      values[1][i] = var_2;
		      values[2][i] = var_0;
		      break;
		    case 4:
		      values[0][i] = var_3;
		      values[1][i] = var_1;
		      values[2][i] = var_0;
		      break;
		    default:
		      values[0][i] = var_0;
		      values[1][i] = var_1;
		      values[2][i] = var_2;
		      break;
		    }
		}
	    }
	}
      for (color = 0; color < 3; color++)
	if (tmp[color])
	  free(tmp[color]);
    }
}

void changeColorDescr(GtkToggleButton *button, gpointer data)
{
  int val;
  
  if (!gtk_toggle_button_get_active(button))
    return;

  val = GPOINTER_TO_INT(data);
  if ( val != COLOUR_DESCR_RGB && val != COLOUR_DESCR_HSV)
    {
      fprintf(stderr, "WARNING! Wrong parameters in call of changeColorDescr.\n");
      return;
    }
  DBG_fprintf(stderr, "Gtk Wire : set color description to %d.\n", val);
  colorDescr = val;
  
  if (val == COLOUR_DESCR_RGB)
    {
      gtk_label_set_text(GTK_LABEL(labelColourDescr[0]), _("R"));
      gtk_label_set_text(GTK_LABEL(labelColourDescr[1]), _("G"));
      gtk_label_set_text(GTK_LABEL(labelColourDescr[2]), _("B"));
    }
  else
    {
      gtk_label_set_text(GTK_LABEL(labelColourDescr[0]), _("H"));
      gtk_label_set_text(GTK_LABEL(labelColourDescr[1]), _("S"));
      gtk_label_set_text(GTK_LABEL(labelColourDescr[2]), _("V"));
    }
}

static void wireValuesChangedOnResources(GObject *obj, gpointer data)
{
  if (!gtkPairs_isPairExtensionInUse(pointerToPairExtension_wire))
    return;

  DBG_fprintf(stderr, "Gtk Wire : catch the 'resourcesLoaded' signal, updating values.\n");
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinThickness), getWireGeneralWidth());
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkNonLinear), getWireNonLinear());
}


/* gboolean drawCoordinates(GtkWidget *widget, GdkEvent *event, gpointer user_data) */
/* { */
/*   int curve; */

/*   curve = GPOINTER_TO_INT(user_data); */
/*   if (curve < 0 || curve > 2) */
/*     { */
/*       fprintf(stderr, "WARNING! Wrong parameters in call of drawCoordinates.\n"); */
/*       return FALSE; */
/*     } */

/*   fprintf(stderr, "%d\n", event->type); */
/*   return FALSE; */
/* } */
