/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD, 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 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.

	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 <support.h>
#include <gtk/gtk.h>
#include <visu_gtk.h>
#include <gtk_main.h>
#include <visu_basic.h>
#include <gtk_renderingWindowWidget.h>
#include <iface_animatable.h>

#include <extraFunctions/vibration.h>
#include <extensions/vibrations.h>

#include "panelVibration.h"

/**
 * SECTION: panelVibration
 * @short_description: The tab where phonons are loaded and listed.
 *
 * <para>Nothing tunable here.</para>
 */

enum {
    NUM_COLUMN,
    FREQ_COLUMN,
    Q_COLUMN,
    ENERGY_COLUMN,
    N_COLUMN
};

/* Local objects. */
static GtkWidget *panelVibration;
static GtkWidget *vboxStart;
static GtkWidget *buttonPlay, *buttonStop, *buttonReset;
static GtkWidget *treeView;
static GtkWidget *checkSpin, *spinAmpl, *spinFreq;

/* Local variables. */
static gboolean widgetsNotBuilt;
static GtkListStore *pListStore;
static VisuVibration *vibs = NULL;
static GBinding *bind_play, *bind_freq, *bind_ampl;

/* Local routines. */
static GtkWidget *createInteriorVibe(VisuGlNodeScene *scene);

/* Local callbacks. */
static void onVibeEnter(VisuUiPanel *visu_ui_panel, gpointer data);
/* static void onDirectoryClicked(GtkButton *button , gpointer data); */
static void onPlayClicked(GtkButton *button, gpointer dataObj);
static void onStopClicked(GtkButton *button, gpointer data);
static void onResetClicked(GtkButton *button , gpointer dataObj);
static void onDataFocused(GObject *obj, VisuData *dataObj, gpointer data);
static void onViewClikcked();
static void onDestroy();
/* static void onFreqChecked(GtkToggleButton *toggle, gpointer data); */

/* Setup the selection handler */
static GtkTreeSelection *treeSelection;
static gulong sel_sig;

/* The string common to all paths in currentBrowseredDirectory. */
static gchar *commonBrowseredDirectory;

VisuUiPanel* visu_ui_panel_vibration_init(VisuUiMain *ui)
{
  VisuGlNodeScene *scene;
  GtkWidget *checkFreq;

  panelVibration = visu_ui_panel_newWithIconFromPath("panel_Vibration", _("Phonons"),
                                                     _("Phonons"), "stock-phonons.png");

  if (!panelVibration)
    return (VisuUiPanel*)0;

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_getRendering(ui));

  visu_ui_panel_setDockable(VISU_UI_PANEL(panelVibration), TRUE);

  vboxStart = gtk_vbox_new(FALSE, 0);
  commonBrowseredDirectory = (char *)0;

  checkSpin =
    gtk_check_button_new_with_mnemonic(_("with _arrow"));

  checkFreq =
    gtk_check_button_new_with_mnemonic(_("use _fixed frequency"));
  g_object_bind_property(scene, "data", checkFreq, "sensitive", G_BINDING_SYNC_CREATE);
  
  /* Create the callbacks of all the sensitive widgets. */
  g_signal_connect(G_OBJECT(panelVibration), "page-entered",
		   G_CALLBACK(onVibeEnter), scene);
  g_signal_connect(G_OBJECT(ui), "DataFocused",
		   G_CALLBACK(onDataFocused), (gpointer)0);

  pListStore = gtk_list_store_new(N_COLUMN, G_TYPE_INT, G_TYPE_FLOAT,
				  G_TYPE_STRING, G_TYPE_FLOAT);
  widgetsNotBuilt  = TRUE;

  return VISU_UI_PANEL(panelVibration);
}

static void onVibeEnter(VisuUiPanel *visu_ui_panel _U_, gpointer data)
{
  if (widgetsNotBuilt)
    {
      DBG_fprintf(stderr, "Panel Vibe: first build on enter.\n");
      widgetsNotBuilt = FALSE;
      gtk_container_add(GTK_CONTAINER(panelVibration),
                        createInteriorVibe(VISU_GL_NODE_SCENE(data)));
    }
}

static GtkWidget *createInteriorVibe(VisuGlNodeScene *scene)
{
  GtkWidget *vbox1;
  GtkWidget /* *hbox1,  */*hbox2, *hbox;
  GtkWidget *label;
/*   GtkWidget *buttonDirectory; */
  GtkWidget *image;
  GtkWidget *scrollbar;
  GtkCellRenderer *CellRender;
  GtkTreeViewColumn *column;
  VisuData *data;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new ();
#endif

  vbox1 = gtk_vbox_new(FALSE, 0);
  /* hbox1 = gtk_hbox_new(FALSE, 0); */
  hbox2 = gtk_hbox_new(FALSE, 0);

  /* the first hbox with the "open-file" button */
/*   gtk_box_pack_start(GTK_BOX(vbox1), hbox1, FALSE, FALSE, 2); */

/*   buttonDirectory = gtk_button_new (); */
/*   gtk_box_pack_start (GTK_BOX (hbox1), buttonDirectory, FALSE, FALSE, 2); */
/*   gtk_widget_set_tooltip_text(buttonDirectory, */
/* 			_("Choose a different directory.")); */
/*   image = gtk_image_new_from_stock ("gtk-open", GTK_ICON_SIZE_BUTTON); */
/*   gtk_container_add (GTK_CONTAINER (buttonDirectory), image); */

/*   label = gtk_label_new("open phonon file"); */
/*   gtk_container_add(GTK_CONTAINER(hbox1), label); */
/*   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); */

  /* the checkboxes */
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox1), hbox, FALSE, FALSE, 0);

  gtk_widget_set_tooltip_text(checkSpin,
			      _("Draw arrows on  nodes that represent"
				" their displacements."));
  g_object_bind_property(visu_gl_node_scene_getVibrations(scene), "active",
                         checkSpin, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), checkSpin, TRUE, TRUE, 0);

/*   gtk_widget_set_tooltip_text(checkFreq, */
/* 			      _("Use a given frequency for the" */
/* 				" vibration representation.")); */
/*   g_signal_connect(G_OBJECT(checkFreq), "toggled", */
/* 		   G_CALLBACK(onFreqChecked), (gpointer)0); */
/*   gtk_box_pack_start(GTK_BOX(hbox), checkFreq, FALSE, FALSE, 0); */
/*   gtk_widget_set_sensitive(checkFreq, FALSE); */

  /* the second hbox with the treeview */
  treeView = gtk_tree_view_new();
  gtk_tree_view_set_model(GTK_TREE_VIEW(treeView), GTK_TREE_MODEL(pListStore));
  CellRender = gtk_cell_renderer_text_new();
  /* when clicking in the treeView */
  treeSelection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeView));
  gtk_tree_selection_set_mode (treeSelection, GTK_SELECTION_SINGLE);

  /* make and add the first column to the view */
  column =  gtk_tree_view_column_new_with_attributes(_("id"), CellRender,
						     "text", NUM_COLUMN,  NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), column);

  /* make and add the second column to the view */
  column =  gtk_tree_view_column_new_with_attributes(_("q point"), CellRender,
						     "text", Q_COLUMN,  NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), column);

  /* make and add the third column to the view */
  column =  gtk_tree_view_column_new_with_attributes(_("energy"), CellRender,
						     "text", ENERGY_COLUMN,  NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), column);

  /* make and add the fourth column to the view */
  column =  gtk_tree_view_column_new_with_attributes("\317\211", CellRender,
						     "text", FREQ_COLUMN,  NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), column);

  /* put the treeview with a scrollbar in the tab*/
  scrollbar = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrollbar),
				 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrollbar),
				      GTK_SHADOW_ETCHED_IN);
  gtk_container_add(GTK_CONTAINER(scrollbar), treeView);
  gtk_box_pack_start(GTK_BOX(vbox1), scrollbar, TRUE, TRUE, 0);

  /* the third hbox with the timer, resetButton and PlayStop Button */
  gtk_box_pack_end(GTK_BOX(vbox1), hbox2, FALSE, FALSE, 2);

  /* the timer */
  label = gtk_label_new(_("Freq.: "));
  gtk_box_pack_start(GTK_BOX(hbox2), label, FALSE, FALSE, 2);
  spinFreq = gtk_spin_button_new_with_range(0, 20, 1);
  gtk_box_pack_start(GTK_BOX(hbox2), spinFreq, FALSE, FALSE, 2);

  /* the amplitude */
  label = gtk_label_new(_("Ampl.: "));
  gtk_box_pack_start(GTK_BOX(hbox2), label, FALSE, FALSE, 2);
  spinAmpl = gtk_spin_button_new_with_range(0, 2, 0.1);
  gtk_box_pack_start(GTK_BOX(hbox2), spinAmpl, FALSE, FALSE, 2);

  /* Stop Button */
  buttonStop = gtk_button_new ();
  gtk_box_pack_end(GTK_BOX (hbox2), buttonStop, FALSE, FALSE, 2);
  gtk_widget_set_tooltip_text(buttonStop,
			      _("Stop the nodes at their given positions."));
  image = gtk_image_new_from_icon_name("nedia-playback-stop", GTK_ICON_SIZE_BUTTON);
  gtk_container_add (GTK_CONTAINER (buttonStop), image);

  /* Play Button */
  buttonPlay = gtk_button_new ();
  gtk_box_pack_end(GTK_BOX (hbox2), buttonPlay, FALSE, FALSE, 2);
  gtk_widget_set_tooltip_text(buttonPlay,
			      _("Move the nodes according to their phonon vibration."));
  image = gtk_image_new_from_icon_name("media-playback-start", GTK_ICON_SIZE_BUTTON);
  gtk_container_add (GTK_CONTAINER (buttonPlay), image);
  gtk_widget_set_sensitive(buttonPlay, FALSE);

  /* reset button */
  buttonReset = gtk_button_new_with_label(_("Reset"));
  gtk_box_pack_end(GTK_BOX (hbox2), buttonReset, FALSE, FALSE, 2);
  gtk_widget_set_tooltip_text(buttonReset,
			_("Reset the node positions to input file coordinates."));

  /* to show all the content of the tab */
  gtk_widget_show_all(vbox1);
  gtk_widget_set_sensitive(buttonPlay, FALSE);
  g_object_bind_property(buttonPlay, "visible", buttonStop, "visible",
                         G_BINDING_SYNC_CREATE | G_BINDING_INVERT_BOOLEAN);

/*   g_signal_connect(G_OBJECT(buttonDirectory), "clicked", */
/* 		   G_CALLBACK(onDirectoryClicked), (gpointer)0); */
  g_signal_connect(G_OBJECT(buttonPlay), "clicked",
		   G_CALLBACK(onPlayClicked), (gpointer)0);
  g_signal_connect(G_OBJECT(treeView), "row-activated",
		   G_CALLBACK(onPlayClicked), (gpointer)0);
  g_signal_connect(G_OBJECT(buttonStop), "clicked",
		   G_CALLBACK(onStopClicked), (gpointer)0);
  g_signal_connect(G_OBJECT(buttonReset), "clicked",
		   G_CALLBACK(onResetClicked), (gpointer)0);
  sel_sig = g_signal_connect(G_OBJECT(treeSelection), "changed",
                             G_CALLBACK(onViewClikcked), (gpointer)0);
  g_signal_connect(G_OBJECT(vbox1), "destroy",
		   G_CALLBACK(onDestroy), (gpointer)0);
 
  data = visu_ui_panel_getData(VISU_UI_PANEL(panelVibration));
  if(data)
    onDataFocused((GObject*)0, data, (gpointer)0);

  return vbox1;
}

static void onDataFocused(GObject *obj _U_, VisuData *dataObj, gpointer data _U_)
{
  VisuVibration *vib;
  gchar *sTexte;
  guint i;
  float qpt[3], en, omega;
  GtkTreeIter pIter;
  guint nSet;

  DBG_fprintf(stderr, "Panel Vibration: caught 'DataFocused' signal (%p).\n",
              (gpointer)dataObj);

  if (widgetsNotBuilt)
    return;

  g_signal_handler_block(treeSelection, sel_sig);
  gtk_list_store_clear(pListStore);
  if (vibs)
    {
      g_object_unref(bind_play);
      g_object_unref(bind_ampl);
      g_object_unref(bind_freq);
      g_object_unref(vibs);
    }
  vib = dataObj ? visu_data_getVibration(dataObj, 0) : (VisuVibration*)0;
  if (vib)
    {
      g_object_ref(vib);

      /* Fill TreeView Model */
      DBG_fprintf(stderr, "panelVibration: filling treeView ...\n");
      nSet = visu_vibration_getNPhonons(vib);
      for (i = 0; i < nSet; i++)
        {
	  visu_vibration_getCharacteristic(vib, i, qpt, &en, &omega);
          sTexte = g_strdup_printf("(%g;%g;%g)", qpt[0], qpt[1], qpt[2]);
          /* Create a new line */
          gtk_list_store_append(pListStore, &pIter);
          /* update data */
          gtk_list_store_set(pListStore, &pIter,
			     NUM_COLUMN, i+1,
			     FREQ_COLUMN, omega,
			     Q_COLUMN, sTexte,
			     ENERGY_COLUMN, en,
			     -1);
	  g_free(sTexte);
	}

      bind_play = g_object_bind_property
        (visu_animatable_getAnimation(VISU_ANIMATABLE(vib), "reduced-time"), "running",
         buttonPlay, "visible", G_BINDING_SYNC_CREATE | G_BINDING_INVERT_BOOLEAN);
      bind_ampl = g_object_bind_property
        (vib, "amplitude",
         spinAmpl, "value", G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      bind_freq = g_object_bind_property
        (vib, "frequency",
         spinFreq, "value", G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
    }
  vibs = vib;
  g_signal_handler_unblock(treeSelection, sel_sig);

  gtk_widget_set_sensitive(checkSpin, (vibs != (VisuVibration*)0));
  gtk_widget_set_sensitive(buttonReset, (vibs != (VisuVibration*)0));
}

/* static void onDirectoryClicked(GtkButton *button _U_, gpointer data _U_) */
/* { */
/*   GtkWidget *file_selector; */
/*   gchar *filename; */
/*   GtkFileFilter *filter; */

/*   file_selector = gtk_file_chooser_dialog_new(_("Choose a file to open"), NULL, */
/* 					      GTK_FILE_CHOOSER_ACTION_OPEN, */
/* 					      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, */
/* 					      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, */
/* 					      NULL); */

/*   filter = gtk_file_filter_new (); */
/*   gtk_file_filter_add_pattern (filter, "*.xyz"); */
/*   gtk_file_chooser_add_filter (GTK_FILE_CHOOSER(file_selector), filter); */

/*   if (gtk_dialog_run (GTK_DIALOG (file_selector)) == GTK_RESPONSE_ACCEPT) */
/*     { */
/*       filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (file_selector)); */
/*     } */
/*   else */
/*     filename = (gchar*)0; */

/*   gtk_widget_destroy (file_selector); */

/*   if (filename) { */
/*     DBG_fprintf(stderr, "panelVibration: opening file \" %s  \" \n", filename); */

/*   } */
/* } */

static void onPlayClicked(GtkButton *button _U_, gpointer timer _U_)
{
  if (!vibs)
    return;

  visu_vibration_animate(vibs);
}

static void onStopClicked(GtkButton *button _U_, gpointer data _U_)
{
  if (!vibs)
    return;

  visu_animation_abort(visu_animatable_getAnimation(VISU_ANIMATABLE(vibs),
                                                    "reduced-time"));
}

static void onResetClicked(GtkButton *button _U_, gpointer dataObj _U_)
{
  DBG_fprintf(stderr, "panelVibration: reseting all nodes position \n");
  onStopClicked(NULL, NULL);
  if (vibs)
    visu_vibration_resetPosition(vibs);
  gtk_tree_selection_unselect_all(treeSelection);
}

static void onViewClikcked() {

  GtkTreeIter iter;
  GtkTreeModel *model;
  int num; 
  GError *error;

  model = GTK_TREE_MODEL(pListStore);
  if (!gtk_tree_selection_get_selected(treeSelection, &model, &iter) || !vibs)
    {
      gtk_widget_set_sensitive(buttonPlay, FALSE);
      return;
    }

  gtk_widget_set_sensitive(buttonPlay, TRUE);

  gtk_tree_model_get(model, &iter, NUM_COLUMN, &num, -1);
  DBG_fprintf(stderr, "Panel Vibration: You have selected a new mode number %d.\n",
	       num);
  error = (GError*)0;
  visu_vibration_setCurrentMode(vibs, (guint)(num - 1), &error);
  if (error)
    {
      visu_ui_raiseWarning(_("Vibration file reloading"), error->message,
			   (GtkWindow*)0);
      g_error_free(error);
      visu_gl_node_scene_setData(visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering()), (VisuData*)0);
      return;
    }
  /* Set the initiale phase properly. */
  visu_vibration_setZeroTime(vibs);

  DBG_fprintf(stderr, "panelVibration: new proper mode loaded.\n");
}

/* static void onFreqChecked(GtkToggleButton *toggle, gpointer data _U_) */
/* { */
/*   if (gtk_toggle_button_get_active(toggle)) */
/*     visu_vibration_setUserFrequency(visu_ui_panel_getData(VISU_UI_PANEL(panelVibration)), 50.f); */
/*   else */
/*     visu_vibration_setUserFrequency(visu_ui_panel_getData(VISU_UI_PANEL(panelVibration)), 0.f); */
/* } */

static void onDestroy()
{
  onDataFocused((GObject*)0, (VisuData*)0, (gpointer)0);
}
