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

#include <string.h>

#include <support.h>
#include <visu_basic.h>
#include <visu_configFile.h>
#include <visu_gtk.h>


/**
 * SECTION: panelConfig
 * @short_description: The tab where miscellaneous options are setup.
 *
 * <para>Nothing special here.</para>
 */

#define FLAG_PARAMETER_SKIN_CONFIG       "config_skin"
#define FLAG_PARAMETER_REFRESH_CONFIG    "config_refreshIsOn"
#define FLAG_PARAMETER_PERIOD_CONFIG     "config_refreshTimeout"
#define FLAG_PARAMETER_OLD_PERIOD_CONFIG "config_refreshPeriod"
#define DESC_PARAMETER_SKIN_CONFIG       "Path to a gtkrc file ; chain"
#define DESC_PARAMETER_REFRESH_CONFIG    "When on V_Sim reloads the file at periodic time ; boolean 0 or 1"
#define DESC_PARAMETER_PERIOD_CONFIG    "The period of reloading in s ; integer (0 < v <= 10)"
#define PARAMETER_CONFIG_SKIN_DEFAULT      "None"
static gchar *_skinDefault = NULL;
#define PARAMETER_CONFIG_REFRESH_DEFAULT   FALSE
static gboolean _refreshDefault = PARAMETER_CONFIG_REFRESH_DEFAULT;
#define PARAMETER_CONFIG_PERIOD_DEFAULT    1
static guint _periodDefault = PARAMETER_CONFIG_PERIOD_DEFAULT;

static GtkWidget *comboUnit, *panelVBox;

/* Private functions. */
static GtkWidget *createInteriorConfig(VisuUiRenderingWindow *window);
static void setSkin(const char* label);

/* These functions write all the element list to export there associated resources. */
static void exportParametersPanelConfig(GString *data,
                                        VisuData* dataObj);
static void onUnitChanged(GtkComboBox *combo, gpointer data);

static void initPanelConfigGtkPart(VisuUiRenderingWindow *window);

static char *defaultSkinPath, *userSkinPath;

static gboolean isPanelConfigInitialized;

/* Specific widgets used in this panel. */
static VisuUiPanel *panelConfig;
static GtkWidget *checkShowTab;
static GtkWidget *checkRefreshAuto = NULL;
static GtkWidget *checkStorePositions;
static GtkWidget *checkRedCoord;
static GtkWidget *spinRefresh = NULL;
static GBinding *autoRefresh_bind = NULL, *periodRefresh_bind = NULL;

/* Callbacks */
static void checkShowTabToggled(GtkToggleButton *button, gpointer data);
static void checkRememberToggled(GtkToggleButton *button, gpointer data);
void entryRcFilesChanged(GtkEntry *entry, gpointer data);
void directorySelectedForResources(GtkButton *button, gpointer user_data);
void openRcFileSelector(GtkButton *button, gpointer data);
static void onDataFocused(GObject *obj, VisuData *dataObj, gpointer data);
gboolean treePathClicked(GtkWidget *widget, GdkEventButton *event, gpointer user_data);
void directoryRemoveFromResources(GtkButton *button, gpointer user_data);
static void onConfigEnter(VisuUiPanel *visu_ui_panel, VisuUiRenderingWindow *window);
static void onEntryRefresh(VisuConfigFile *obj, VisuConfigFileEntry *entry, gpointer data);
static void onEntryPeriod(VisuConfigFile *obj, VisuConfigFileEntry *entry, gpointer data);
static void onEntrySkin(VisuConfigFile *obj, VisuConfigFileEntry *entry, gpointer data);

/**
 * visu_ui_panel_config_init: (skip)
 * @ui: a #VisuUiMain object.
 *
 * 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 configuration
 * stuff can be done, such as the auto-reloading.
 *
 * Returns: a newly created #VisuUiPanel object.
 */
VisuUiPanel* visu_ui_panel_config_init(VisuUiMain *ui)
{
  char *cl = _("Configure the interface");
  char *tl = _("Configuration");
  int rgPeriod[2] = {1, 10};
  VisuConfigFileEntry *entry, *oldEntry;

  panelConfig = VISU_UI_PANEL(visu_ui_panel_newWithIconFromIconName("Panel_configuration",
                                                                    cl, tl,
                                                                    "preferences-system"));
  if (!panelConfig)
    return (VisuUiPanel*)0;

  visu_config_file_addStringEntry(VISU_CONFIG_FILE_PARAMETER,
                                  FLAG_PARAMETER_SKIN_CONFIG,
                                  DESC_PARAMETER_SKIN_CONFIG,
                                  &_skinDefault);
  g_signal_connect(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_SKIN_CONFIG,
                   G_CALLBACK(onEntrySkin), panelConfig);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                   FLAG_PARAMETER_REFRESH_CONFIG,
                                   DESC_PARAMETER_REFRESH_CONFIG,
                                   &_refreshDefault, FALSE);
  g_signal_connect(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_REFRESH_CONFIG,
                   G_CALLBACK(onEntryRefresh), panelConfig);
  oldEntry = visu_config_file_addEntry(VISU_CONFIG_FILE_PARAMETER,
                                       FLAG_PARAMETER_OLD_PERIOD_CONFIG,
                                       DESC_PARAMETER_PERIOD_CONFIG,
                                       1, NULL);
  entry = visu_config_file_addIntegerArrayEntry(VISU_CONFIG_FILE_PARAMETER,
                                                FLAG_PARAMETER_PERIOD_CONFIG,
                                                DESC_PARAMETER_PERIOD_CONFIG,
                                                1, (int*)&_periodDefault, rgPeriod, FALSE);
  visu_config_file_entry_setVersion(entry, 3.8f);
  visu_config_file_entry_setReplace(entry, oldEntry);
  g_signal_connect(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_PERIOD_CONFIG,
                   G_CALLBACK(onEntryPeriod), panelConfig);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_PARAMETER,
                                     exportParametersPanelConfig);

#if GTK_MAJOR_VERSION < 3
  defaultSkinPath = g_build_filename(visu_basic_getDataDir(), "v_sim.rc", NULL);
  userSkinPath    = g_build_filename(visu_basic_getLocalDir(), "v_sim.rc", NULL);
#else
  defaultSkinPath = g_build_filename(visu_basic_getDataDir(), "v_sim.css", NULL);
  userSkinPath    = g_build_filename(visu_basic_getLocalDir(), "v_sim.css", NULL);
#endif

  isPanelConfigInitialized = FALSE;

  /* Set global callbacks. */
  g_signal_connect(G_OBJECT(ui), "DataFocused",
		   G_CALLBACK(onDataFocused), (gpointer)0);
  g_signal_connect(G_OBJECT(panelConfig), "page-entered",
		   G_CALLBACK(onConfigEnter), (gpointer)visu_ui_main_getRendering(ui));

  return panelConfig;
}

static void initPanelConfigGtkPart(VisuUiRenderingWindow *window)
{
  if (isPanelConfigInitialized)
    return;

  DBG_fprintf(stderr, "Panel Config : creating the config panel on demand.\n");
  isPanelConfigInitialized = TRUE;

  panelVBox = createInteriorConfig(window);
  gtk_container_add(GTK_CONTAINER(panelConfig), panelVBox);

  /* Force the callbacks to initialise the values. */
  checkShowTabToggled((GtkToggleButton*)0, (gpointer)0);
}


static GtkWidget *createInteriorConfig(VisuUiRenderingWindow *window)
{
  GtkWidget *vbox;
  GtkWidget *hbox;
  GtkWidget *label;
  const gchar **units;
  int i;
 
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12 
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new ();
#endif

  vbox = gtk_vbox_new(FALSE, 0);

  checkShowTab = gtk_check_button_new_with_mnemonic(_("Always show _labels in tabs"));
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkShowTab),
			       visu_ui_panel_class_getHeaderVisibility());
  gtk_box_pack_start(GTK_BOX(vbox), checkShowTab, FALSE, FALSE, 3);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);
  checkRefreshAuto = gtk_check_button_new_with_mnemonic(_("Automatic _refresh"));
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkRefreshAuto),
			       _refreshDefault);
  gtk_box_pack_start(GTK_BOX(hbox), checkRefreshAuto, FALSE, FALSE, 0);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);
  label = gtk_label_new(_(" s"));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
  spinRefresh = gtk_spin_button_new_with_range(1., 10., 1.);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinRefresh), _periodDefault);
  gtk_box_pack_end(GTK_BOX(hbox), spinRefresh, FALSE, FALSE, 0);
  label = gtk_label_new(_("period:"));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);
  checkStorePositions = gtk_check_button_new_with_mnemonic(_("Remember _windows positions"));
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkStorePositions),
			       (gboolean)TRUE);
  gtk_box_pack_start(GTK_BOX(hbox), checkStorePositions, FALSE, FALSE, 0);

  checkRedCoord = gtk_check_button_new_with_mnemonic(_("Display _coordinates in reduce"));
  g_object_bind_property(window, "coordinates-in-reduced",
                         checkRedCoord, "active", G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(vbox), checkRedCoord, FALSE, FALSE, 3);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 3);
  label = gtk_label_new(_("Set the prefered unit:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 5);

  comboUnit = gtk_combo_box_text_new();
  units = tool_physic_getUnitNames();
  for (i = 0; units[i]; i++)
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(comboUnit), (const gchar*)0, units[i]);
  gtk_combo_box_set_active(GTK_COMBO_BOX(comboUnit), visu_basic_getPreferedUnit());
  g_signal_connect(G_OBJECT(comboUnit), "changed",
		   G_CALLBACK(onUnitChanged), (gpointer)0);
  gtk_box_pack_start(GTK_BOX(hbox), comboUnit, FALSE, FALSE, 0);

  /* Set the callbacks. */
  g_signal_connect(G_OBJECT(checkShowTab), "toggled",
		   G_CALLBACK(checkShowTabToggled), (gpointer)0);
  g_signal_connect(G_OBJECT(checkStorePositions), "toggled",
		   G_CALLBACK(checkRememberToggled), (gpointer)0);
    
  gtk_widget_show_all(vbox);
  return vbox;
}

/*************/
/* Callbacks */
/*************/
static void checkShowTabToggled(GtkToggleButton *button _U_, gpointer data _U_)
{
  visu_ui_panel_class_setHeaderVisibility(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkShowTab)));
}
static void checkRememberToggled(GtkToggleButton *button, gpointer data _U_)
{
  visu_ui_main_class_setRememberPosition(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button)));
}
static void onConfigEnter(VisuUiPanel *visu_ui_panel _U_, VisuUiRenderingWindow *window)
{
  if (!isPanelConfigInitialized)
    initPanelConfigGtkPart(window);

  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkStorePositions),
			       visu_ui_main_class_getRememberPosition());
}
void openRcFileSelector(GtkButton *button _U_, gpointer data _U_)
{
}
static void setSkin(const char* label)
{
  const char *tmp;
#if GTK_MAJOR_VERSION < 3
  GtkSettings *settings;
#else
  GError *error;
  GtkCssProvider *css;
#endif

  if (!label || label[0] == '\0' || !strcmp(label, "None"))
    return;

  if (!strcmp(label, "V_Sim"))
    {
      /* We try first a skin in the user config path. */
      if (g_file_test(userSkinPath, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
	tmp = userSkinPath;
      else
	tmp = defaultSkinPath;
    }
  else
    tmp = label;

  /* test if the file exists or fall back on default installation path */
  DBG_fprintf(stderr,"Panel Config: Reading rc file '%s' ... %d\n",
	      tmp, g_file_test(tmp, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR));
  if (!g_file_test(tmp, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
    return;

#if GTK_MAJOR_VERSION < 3
  gtk_rc_parse(tmp);
  DBG_fprintf(stderr, "Panel Config: get the settings.\n");
  settings = gtk_settings_get_default ();
  gtk_rc_reparse_all_for_settings(settings, TRUE);
  DBG_fprintf(stderr,"Panel Config: applying RC file OK.\n");
#else
  css = gtk_css_provider_new();
  error = (GError*)0;
  gtk_css_provider_load_from_path(css, tmp, &error);
  if (error)
    {
      g_warning("%s", error->message);
      g_error_free(error);
    }
  DBG_fprintf(stderr, "Panel Config: CSS file loaded.\n");
  gtk_style_context_add_provider_for_screen(gdk_screen_get_default(),
                                            GTK_STYLE_PROVIDER(css),
                                            GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
  g_object_unref(G_OBJECT(css));
  gtk_style_context_reset_widgets(gdk_screen_get_default());
#endif
}
static void onDataFocused(GObject *obj _U_, VisuData *dataObj, gpointer data _U_)
{
  gboolean isLoadable;

  DBG_fprintf(stderr, "Panel Config: caught the 'DataFocused' signal\n");
  if (!dataObj)
    return;

  isLoadable = VISU_IS_DATA_LOADABLE(dataObj);

  if (checkRefreshAuto && spinRefresh)
    {
      gtk_widget_set_sensitive(checkRefreshAuto, isLoadable);
      gtk_widget_set_sensitive(spinRefresh, isLoadable);
      if (!isLoadable)
        return;

      if (autoRefresh_bind)
        g_object_unref(autoRefresh_bind);
      autoRefresh_bind =
        g_object_bind_property(checkRefreshAuto, "active", dataObj, "auto-refresh",
                               G_BINDING_SYNC_CREATE & G_BINDING_BIDIRECTIONAL);
      if (periodRefresh_bind)
        g_object_unref(periodRefresh_bind);
      periodRefresh_bind =
        g_object_bind_property(spinRefresh, "value", dataObj, "refresh-period",
                               G_BINDING_SYNC_CREATE & G_BINDING_BIDIRECTIONAL);
    }
  else if (isLoadable)
    g_object_set(dataObj, "auto-refresh", _refreshDefault,
                 "refresh-period", _periodDefault, NULL);
}
static void onUnitChanged(GtkComboBox *combo, gpointer data _U_)
{
  visu_basic_setPreferedUnit(gtk_combo_box_get_active(combo));
}



/**********************************/
/* Public method to change values */
/**********************************/
/**
 * visu_ui_panel_config_getArea:
 *
 * This routine can be used to extend the configure panel from plug-ins.
 *
 * Since: 3.7
 *
 * Returns: (transfer none): a #GtkBox containing elements of the
 * configure panel.
 **/
GtkWidget* visu_ui_panel_config_getArea()
{
  if (!isPanelConfigInitialized)
    initPanelConfigGtkPart(visu_ui_main_class_getDefaultRendering());
  
  return panelVBox;
}

/********************/
/* In/Out functions */
/********************/

static void onEntrySkin(VisuConfigFile *obj _U_, VisuConfigFileEntry *entry _U_, gpointer data _U_)
{
  setSkin(_skinDefault);
}
static void onEntryRefresh(VisuConfigFile *obj _U_, VisuConfigFileEntry *entry _U_, gpointer data)
{
  VisuData *dataObj;

  dataObj = visu_ui_panel_getData(VISU_UI_PANEL(data));
  if (VISU_IS_DATA_LOADABLE(dataObj))
    g_object_set(dataObj, "auto-refresh", _refreshDefault, NULL);
}
static void onEntryPeriod(VisuConfigFile *obj _U_, VisuConfigFileEntry *entry _U_, gpointer data)
{
  VisuData *dataObj;

  dataObj = visu_ui_panel_getData(VISU_UI_PANEL(data));
  if (VISU_IS_DATA_LOADABLE(dataObj))
    g_object_set(dataObj, "refresh-period", _periodDefault, NULL);
}

/* These functions write all the element list to export there associated resources. */
static void exportParametersPanelConfig(GString *data,
                                        VisuData *dataObj _U_)
{
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_SKIN_CONFIG);
  g_string_append_printf(data, "%s[gtk]: %s\n\n", FLAG_PARAMETER_SKIN_CONFIG,
			 _skinDefault);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_REFRESH_CONFIG);
  g_string_append_printf(data, "%s[gtk]: %d\n\n", FLAG_PARAMETER_REFRESH_CONFIG,
			 (checkRefreshAuto) ? gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkRefreshAuto)) : _refreshDefault);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_PERIOD_CONFIG);
  g_string_append_printf(data, "%s[gtk]: %i\n\n", FLAG_PARAMETER_PERIOD_CONFIG,
			 (spinRefresh) ? gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(spinRefresh)) : (int)_periodDefault);
}

