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

#include <math.h>

#include <visu_gtk.h>
#include <support.h>
#include <gtk_main.h>
#include <openGLFunctions/objectList.h>
#include <coreTools/toolMatrix.h>
#include <extensions/planes.h>

#include <extraGtkFunctions/gtk_toolPanelWidget.h>
#include <extraGtkFunctions/gtk_colorComboBoxWidget.h>
#include <extraGtkFunctions/gtk_numericalEntryWidget.h>
#include <extraGtkFunctions/gtk_orientationChooser.h>
#include <extraGtkFunctions/gtk_valueIOWidget.h>

#include <uiElements/ui_planetree.h>

/**
 * SECTION: panelPlanes
 * @short_description: The tab where planes are defined.
 *
 * <para>It is possible to get the list of planes using
 * visu_ui_panel_planes_getModel(). One can also access to the list
 * store hosting the planes by calling visu_ui_panel_planes_getList().</para>
 */

#define PANEL_PLANES_NO_VISU_PLANE_LIST _("<span font_desc=\"smaller\"><i>none</i></span>")

static GtkWidget *panelPlanes;
static GtkWidget *vBoxVisuPlanes;
static GtkWidget *checkUseVisuPlanes;
static GtkWidget *entryDistFrom, *entryDistTo, *entryDistStep, *spinDistDelay;
static GtkWidget *imageDistPlay, *imageDistStop;
static GtkWidget *valueIO;

static guint isPlayingDistanceId;
static gdouble directionDist;

/* Local callbacks. */
static void onSetCameraPosition(VisuUiPlaneList *list, VisuPlane *plane, gpointer data);
static void onPlayStopDist(GtkButton *button, gpointer data);
static void onSpinDistDelayChange(GtkSpinButton *spin, gpointer data);
static void onVisuPlanesEnter(VisuUiPanel *ui, VisuGlExtPlanes *planes);

/* Local methods. */
static void stopPlayStop(gpointer data);
static gboolean playDistances(gpointer data);
/* Call createInteriorVisuPlanes() to create all the widgets,
   and if dataObj is not null, it set callbacks as if
   a new VisuData has been loaded. */
static void createInteriorVisuPlanes(VisuGlExtPlanes *planes);
static gboolean callbackOpen(const gchar* filename, GError **error);
static gboolean callbackSave(const gchar* filename, GError **error);

static gboolean isVisuPlanesInitialised;
static VisuUiPlaneList *store;

/**
 * visu_ui_panel_planes_init: (skip)
 *
 * Should be used in the list declared in externalModules.h to be loaded by
 * V_Sim on start-up. This routine will create the #VisuUiPanel where the plane
 * stuff can be done, such as creating a plane, masking nodes,
 * changing the orientation or the colour...
 *
 * Returns: a newly created #VisuUiPanel object.
 */
VisuUiPanel* visu_ui_panel_planes_init(VisuUiMain *ui)
{
  /* Long description */
  char *cl = _("Drawing planes");
  /* Short description */
  char *tl = _("Planes");
  VisuGlNodeScene *scene;
  VisuGlExtPlanes *planes;

  panelPlanes = visu_ui_panel_newWithIconFromPath("Panel_planes", cl, tl,
                                                  "stock-planes_20.png");
  if (!panelPlanes)
    return (VisuUiPanel*)0;
  visu_ui_panel_setDockable(VISU_UI_PANEL(panelPlanes), TRUE);

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_getRendering(ui));

  vBoxVisuPlanes = gtk_vbox_new (FALSE, 2);
  g_object_bind_property(scene, "data", vBoxVisuPlanes, "sensitive", G_BINDING_SYNC_CREATE);

  isVisuPlanesInitialised = FALSE;
  checkUseVisuPlanes      = (GtkWidget*)0;

  store = visu_ui_plane_list_new();
  planes = visu_gl_node_scene_addPlanes(scene);
  visu_ui_plane_list_setModel(store, planes->planes);
  g_signal_connect(G_OBJECT(store), "align", G_CALLBACK(onSetCameraPosition), (gpointer)0);

  isPlayingDistanceId = 0;
  valueIO = visu_ui_value_io_new(visu_ui_panel_getContainerWindow(VISU_UI_PANEL(panelPlanes)),
                                 _("Import planes from an existing XML file."),
                                 _("Export planes to the current XML file."),
                                 _("Export planes to a new XML file."));
  visu_ui_value_io_connectOnOpen(VISU_UI_VALUE_IO(valueIO), callbackOpen);
  visu_ui_value_io_setSensitiveOpen(VISU_UI_VALUE_IO(valueIO), TRUE);
  visu_ui_value_io_connectOnSave(VISU_UI_VALUE_IO(valueIO), callbackSave);
  g_object_bind_property(planes->planes, "n-planes",
                         valueIO, "sensitive-save", G_BINDING_SYNC_CREATE);

  /* Add the signal for the vBoxVisuPlanes. */
  g_signal_connect(G_OBJECT(panelPlanes), "page-entered",
		   G_CALLBACK(onVisuPlanesEnter), planes);
  g_signal_connect_swapped(G_OBJECT(panelPlanes), "destroy",
                           G_CALLBACK(g_object_unref), store);

  return VISU_UI_PANEL(panelPlanes);
}

/**
 * visu_ui_panel_planes_getList:
 * 
 * This method gives read access to the #GtkListStore used to store
 * the planes.
 *
 * Returns: (transfer none): the #GtkListStore used by this panel to
 * store its planes. It should be considered read-only.
 */
GtkListStore* visu_ui_panel_planes_getList()
{
  return GTK_LIST_STORE(store);
}

static void onVisuPlanesEnter(VisuUiPanel *ui _U_, VisuGlExtPlanes *planes)
{
  DBG_fprintf(stderr, "Panel VisuPlanes: caught the 'page-entered' signal %d.\n",
	      isVisuPlanesInitialised);
  if (!isVisuPlanesInitialised)
    {
      createInteriorVisuPlanes(planes);
      isVisuPlanesInitialised = TRUE;
    }
}

static void createInteriorVisuPlanes(VisuGlExtPlanes *planes)
{
  GtkWidget *hbox;
  GtkWidget *label;
  GtkWidget *vbox;
  GtkWidget *buttonDistPlayStop;
  GtkWidget *notebook;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new ();
#endif

  gtk_container_set_border_width(GTK_CONTAINER(vBoxVisuPlanes), 5);

  checkUseVisuPlanes = gtk_check_button_new_with_mnemonic(_("_Use planes"));
  gtk_box_pack_start (GTK_BOX (vBoxVisuPlanes), checkUseVisuPlanes, FALSE, FALSE, 0);
  g_object_bind_property(planes, "active", checkUseVisuPlanes, "active",
                         G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE);

  gtk_box_pack_start(GTK_BOX(vBoxVisuPlanes), visu_ui_plane_list_getView(store), TRUE, TRUE, 0);

  gtk_box_pack_start(GTK_BOX(vBoxVisuPlanes), valueIO, FALSE, FALSE, 0);

  notebook = gtk_notebook_new();
  gtk_box_pack_start(GTK_BOX(vBoxVisuPlanes), notebook, FALSE, FALSE, 0);

  /* Page 1  : simple tools*/
  vbox = GTK_WIDGET(visu_ui_plane_list_getControls(store));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Simple tools")));

  /* Page   : advanced tools*/
  vbox = gtk_vbox_new(FALSE, 0);
  g_object_bind_property(store, "selection", vbox, "sensitive", G_BINDING_SYNC_CREATE);
  label = gtk_label_new(_("Advanced tools"));
  gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, label);

  label = gtk_label_new(_("Change selected plane distance"));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 3);
  hbox = gtk_hbox_new(FALSE, 0);

  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("From: "));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  entryDistFrom = visu_ui_numerical_entry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryDistFrom), 7);
  gtk_box_pack_start(GTK_BOX(hbox), entryDistFrom, FALSE, FALSE, 0);
  label = gtk_label_new(_("to: "));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  entryDistTo = visu_ui_numerical_entry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryDistTo), 7);
  gtk_box_pack_start(GTK_BOX(hbox), entryDistTo, FALSE, FALSE, 0);
  label = gtk_label_new(_("step: "));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  entryDistStep = visu_ui_numerical_entry_new(1.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryDistStep), 7);
  gtk_box_pack_start(GTK_BOX(hbox), entryDistStep, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new (_("Play at "));
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  spinDistDelay = gtk_spin_button_new_with_range(10, 10000, 25);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinDistDelay), 500.);
  gtk_box_pack_start(GTK_BOX(hbox), spinDistDelay, FALSE, TRUE, 0);
  gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(spinDistDelay), TRUE);
  label = gtk_label_new(_(" ms"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  buttonDistPlayStop = gtk_button_new();
  gtk_widget_set_tooltip_text(buttonDistPlayStop,
		       _("Change the distance parameter of he selected file"
			 " at the given rate."));
  gtk_box_pack_start(GTK_BOX(hbox), buttonDistPlayStop, FALSE, FALSE, 15);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_container_add(GTK_CONTAINER(buttonDistPlayStop), hbox);
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 5
  imageDistPlay = create_pixmap((GtkWidget*)0, "stock_media-play.png");
  imageDistStop = create_pixmap((GtkWidget*)0, "stock_media-stop.png");
#else
  imageDistPlay = gtk_image_new_from_icon_name("media-playback-start", GTK_ICON_SIZE_BUTTON);
  imageDistStop = gtk_image_new_from_icon_name("media-playback-stop", GTK_ICON_SIZE_BUTTON);
#endif
  gtk_widget_set_no_show_all(imageDistPlay, TRUE);
  gtk_widget_set_no_show_all(imageDistStop, TRUE);
  gtk_widget_show(imageDistPlay);
  gtk_box_pack_start(GTK_BOX(hbox), imageDistPlay, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), imageDistStop, TRUE, TRUE, 0);

  /* Add the callback methods. */
  g_signal_connect(G_OBJECT(buttonDistPlayStop), "clicked",
		   G_CALLBACK(onPlayStopDist), (gpointer)0);
  g_signal_connect(G_OBJECT(spinDistDelay), "value-changed",
		   G_CALLBACK(onSpinDistDelayChange), (gpointer)0);

  gtk_widget_show_all(vBoxVisuPlanes);

  gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), 0);

  gtk_container_add(GTK_CONTAINER(panelPlanes), vBoxVisuPlanes);
}

static void onSetCameraPosition(VisuUiPlaneList *list _U_, VisuPlane *plane, gpointer data _U_)
{
  float spherical[3];
  float nVisuPlane[3];

  DBG_fprintf(stderr, "Panel VisuPlanes: Set the camera position to be"
              " normal to the selected plane (%p).\n", (gpointer)plane);
  visu_plane_getNVectUser(plane, nVisuPlane);
  tool_matrix_cartesianToSpherical(spherical, nVisuPlane);
  g_object_set(visu_ui_panel_getView(VISU_UI_PANEL(panelPlanes)),
               "theta", spherical[1], "phi", spherical[2], NULL);
}

static void stopPlayStop(gpointer data _U_)
{
  isPlayingDistanceId = 0;
  gtk_widget_hide(imageDistStop);
  gtk_widget_show(imageDistPlay);
}
static void startPlayStop(VisuPlane *plane)
{
  gtk_widget_hide(imageDistPlay);
  gtk_widget_show(imageDistStop);
  isPlayingDistanceId =
    g_timeout_add_full(G_PRIORITY_DEFAULT + 30,
                       (gint)gtk_spin_button_get_value(GTK_SPIN_BUTTON(spinDistDelay)),
                       playDistances, (gpointer)plane,
                       stopPlayStop);
}
static void onPlayStopDist(GtkButton *button _U_, gpointer data _U_)
{
  VisuPlane *plane;

  DBG_fprintf(stderr, "Panel VisuPlanes: push the play/stop button.\n");

  if (!isPlayingDistanceId)
    {
      plane = visu_ui_plane_list_getSelection(store);
      if (plane)
        {
          visu_plane_setDistanceFromOrigin(plane, visu_ui_numerical_entry_getValue(VISU_UI_NUMERICAL_ENTRY(entryDistFrom)));
          directionDist = 1.;
          /* Launch play */
          startPlayStop(plane);
        }
    }
  else
    {
      /* Stop play */
      g_source_remove(isPlayingDistanceId);
    }
}
static gboolean playDistances(gpointer data)
{
  gdouble val, step;
  gboolean changed;
  
  val = visu_plane_getDistanceFromOrigin(VISU_PLANE(data));
  step = visu_ui_numerical_entry_getValue(VISU_UI_NUMERICAL_ENTRY(entryDistStep));
  changed = FALSE;
  if (directionDist > 0.)
    {
      if (val + step > visu_ui_numerical_entry_getValue(VISU_UI_NUMERICAL_ENTRY(entryDistTo)))
	directionDist = -1.;
      else
	changed = TRUE;
    }
  else
    changed = TRUE;
  if (directionDist < 0.)
    {
      if (val - step < visu_ui_numerical_entry_getValue(VISU_UI_NUMERICAL_ENTRY(entryDistFrom)))
	directionDist = +1.;
      else
	changed = TRUE;
    }
  /* If the direction has been changed twice in a row,
     then the step is too wide for the range, we stop. */
  if (!changed)
    return FALSE;

  DBG_fprintf(stderr, "Panel VisuPlanes: set new distance to %g.\n", val + directionDist * step);
  visu_plane_setDistanceFromOrigin(VISU_PLANE(data), val + directionDist * step);
  return TRUE;
}
static void onSpinDistDelayChange(GtkSpinButton *spin _U_, gpointer data _U_)
{
  if (isPlayingDistanceId)
    {
      /* Stop play. */
      g_source_remove(isPlayingDistanceId);
      /* Launch play. */
      startPlayStop(visu_ui_plane_list_getSelection(store));
    }
}

gboolean callbackOpen(const gchar *filename, GError **error)
{
  return visu_plane_set_parseXMLFile(visu_ui_plane_list_getModel(store), filename, error);
}
static gboolean callbackSave(const gchar* filename, GError **error)
{
  return visu_plane_set_exportXMLFile(visu_ui_plane_list_getModel(store), filename, error);
}
