/*   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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <unistd.h> /* For the access markers R_OK, W_OK ... */

#include "gtk_save.h"

#include "gtk_main.h"
#include "visu_configFile.h"
#include "visu_object.h"
#include "visu_tools.h"

static guint saveResourcesContextId, saveParametersContextId;
static gchar *lastEntryResources;

/* Local Callbacks. */
void onLoadResButtonClicked(GtkButton *button, gpointer data);
void onSaveResButtonClicked(GtkButton *button, gpointer data);
void onSelectionResourcesChange(GtkFileChooser *fileChooser, gpointer *data);
void onLoadResourcesSelected(GtkFileChooser *fileChooser, gpointer *data);
void onTextEntryChange(GtkEditable *entry, gpointer data);

void onSaveParButtonClicked(GtkButton *button, gpointer data);

/* Local methods. */
void showAlertMessage(GtkWidget *saveDialog, gchar* message, gboolean warning, int type);
void saveAction(int type, GtkWidget *saveDialog, GtkEntry *entry);

/* The completion tree model. */
enum
  {
    GTK_SAVE_FILE_NAME,
    GTK_SAVE_NB_COLUMNS
  };

void gtkSaveInit()
{
  GtkWidget *saveDialog;
  GtkWidget *wd;
  GtkEntryCompletion *completion;
  gchar *directory, *file;
  GList *resList;
  GtkListStore *listOfFiles;

  saveDialog = create_saveDialog();
  gtk_widget_set_name(saveDialog, "message");

  /* Set style. */
  wd = lookup_widget(saveDialog, "labelSaveDialog");
  gtk_widget_set_name(wd, "message_title");

  wd = lookup_widget(saveDialog, "notebookSave");
  gtk_widget_set_name(wd, "message_notebook");

  wd = lookup_widget(saveDialog, "labelResources");
  gtk_widget_set_name(wd, "label_head");
  wd = lookup_widget(saveDialog, "labelParameters");
  gtk_widget_set_name(wd, "label_head");

  wd = lookup_widget(saveDialog, "imageWarningResources");
  gtk_widget_hide(wd);
  wd = lookup_widget(saveDialog, "imageWarningParameters");
  gtk_widget_hide(wd);

  wd = lookup_widget(saveDialog, "statusbarResources");
  gtk_widget_set_name(wd, "message_statusbar");
  wd = lookup_widget(saveDialog, "statusbarParameters");
  gtk_widget_set_name(wd, "message_statusbar");

  wd = lookup_widget(saveDialog, "labelHelp");
  gtk_widget_set_name(wd, "label_info");
  wd = lookup_widget(saveDialog, "labelHelpTips");
  gtk_widget_set_name(wd, "label_info");

  /* Local variables. */
  listOfFiles = gtk_list_store_new(GTK_SAVE_NB_COLUMNS,
				   G_TYPE_STRING);
  gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(listOfFiles),
				       GTK_SAVE_FILE_NAME, GTK_SORT_ASCENDING);
  lastEntryResources = (gchar*)0;

  /* Set initial values. */
  wd = lookup_widget(saveDialog, "filechooserwidgetResources");
  directory = getLastOpenDirectory();
  if (directory)
    gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(wd), directory);
  g_signal_connect(G_OBJECT(wd), "selection-changed",
		   G_CALLBACK(onSelectionResourcesChange),
		   (gpointer)lookup_widget(saveDialog, "buttonLoadResources"));
  g_signal_connect(G_OBJECT(wd), "file-activated",
		   G_CALLBACK(onLoadResourcesSelected), (gpointer)saveDialog);

  wd = lookup_widget(saveDialog, "statusbarResources");
  saveResourcesContextId = gtk_statusbar_get_context_id(GTK_STATUSBAR(wd), "Resources");


  wd = lookup_widget(saveDialog, "comboboxentryParameters");
  gtk_widget_set_name(wd, "message_entry");
  resList = visuConfigFileGet_pathList(VISU_CONFIGFILE_PARAMETER);
  if (resList)
    {
      do
	{
	  file = visuConfigFileGet_nextValidPath(VISU_CONFIGFILE_PARAMETER, W_OK, &resList, 1);
	  if (file)
	    gtk_combo_box_append_text(GTK_COMBO_BOX(wd), file);
	}
      while(file);
    }
  gtk_combo_box_set_active(GTK_COMBO_BOX(wd), 0);


  wd = lookup_widget(saveDialog, "comboboxentryResources");
  gtk_widget_set_name(wd, "message_entry");
  resList = visuConfigFileGet_pathList(VISU_CONFIGFILE_RESOURCE);
  if (resList)
    {
      do
	{
	  file = visuConfigFileGet_nextValidPath(VISU_CONFIGFILE_RESOURCE, W_OK, &resList, 1);
	  if (file)
	    gtk_combo_box_append_text(GTK_COMBO_BOX(wd), file);
	}
      while(file);
    }
  completion = gtk_entry_completion_new();
  gtk_entry_completion_set_model(completion, GTK_TREE_MODEL(listOfFiles));
  gtk_entry_completion_set_text_column(completion, GTK_SAVE_FILE_NAME);
  gtk_entry_set_completion(GTK_ENTRY(GTK_BIN(wd)->child), completion);
  g_signal_connect(G_OBJECT(GTK_BIN(wd)->child), "changed",
		   G_CALLBACK(onTextEntryChange), (gpointer)0);
  gtk_combo_box_set_active(GTK_COMBO_BOX(wd), 0);

  /* Set callbacks. */
  wd = lookup_widget(saveDialog, "buttonLoadResources");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onLoadResButtonClicked), (gpointer)saveDialog);
  wd = lookup_widget(saveDialog, "buttonSaveResources");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onSaveResButtonClicked), (gpointer)saveDialog);
  wd = lookup_widget(saveDialog, "buttonSaveParameters");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onSaveParButtonClicked), (gpointer)saveDialog);

  /* Run the dialog. */
  gtk_dialog_run(GTK_DIALOG(saveDialog));
  gtk_widget_destroy(saveDialog);
}

void onLoadResourcesSelected(GtkFileChooser *fileChooser, gpointer *data)
{
  onLoadResButtonClicked((GtkButton*)0, data);
}

void onSelectionResourcesChange(GtkFileChooser *fileChooser, gpointer *data)
{
  gchar *filename;

  g_return_if_fail(GTK_BUTTON(data));
  
  filename = gtk_file_chooser_get_filename(fileChooser);
  if (!filename)
    {
      gtk_widget_set_sensitive(GTK_WIDGET(data), FALSE);
      return;
    }

  DBG_fprintf(stderr, "Gtk Save : selected a new potential"
	      " resources file : '%s'.\n", filename);
  gtk_widget_set_sensitive(GTK_WIDGET(data),
			   !g_file_test(filename, G_FILE_TEST_IS_DIR));
  g_free(filename);
}

void onLoadResButtonClicked(GtkButton *button, gpointer data)
{
  GtkWidget *file_selector, *wd;
  gchar *filename, *basename;
  gchar *directory;
  int res;
  GString *errorMessage, *message;

  g_return_if_fail(GTK_DIALOG(data));

  file_selector = lookup_widget(GTK_WIDGET(data), "filechooserwidgetResources");
  g_return_if_fail(file_selector);

  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file_selector));
  directory = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(file_selector));
  setLastOpenDirectory(directory);
  g_free(directory);

  errorMessage = (GString*)0;
  res = visuConfigFileLoad(VISU_CONFIGFILE_RESOURCE, filename, &errorMessage);
  if (!res && errorMessage)
    raiseAlertDialogWithScrollView(errorMessage->str);
  if (errorMessage)
    g_string_free(errorMessage, TRUE);

  basename = g_path_get_basename(filename);
  message = g_string_new("");
  if (res)
    g_string_append_printf(message, _("File '%s' succesfully loaded."), basename);
  else
    g_string_append_printf(message, _("WARNING! File '%s' not loaded."), basename);
  showAlertMessage(GTK_WIDGET(data), message->str, !res, VISU_CONFIGFILE_RESOURCE);
  g_string_free(message, TRUE);
  g_free(basename);

  if (res)
    g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		   0 , NULL);
  g_free (filename);
}

void onSaveResButtonClicked(GtkButton *button, gpointer data)
{
  GtkWidget *entry;

  g_return_if_fail(GTK_DIALOG(data));

  entry = GTK_BIN(lookup_widget(GTK_WIDGET(data), "comboboxentryResources"))->child;
  saveAction(VISU_CONFIGFILE_RESOURCE, GTK_WIDGET(data), GTK_ENTRY(entry));
}

void onSaveParButtonClicked(GtkButton *button, gpointer data)
{
  GtkWidget *entry;

  g_return_if_fail(GTK_DIALOG(data));

  entry = GTK_BIN(lookup_widget(GTK_WIDGET(data), "comboboxentryParameters"))->child;
  saveAction(VISU_CONFIGFILE_PARAMETER, GTK_WIDGET(data), GTK_ENTRY(entry));
}

void saveAction(int type, GtkWidget *saveDialog, GtkEntry *entry)
{
  GtkWidget *wd;
  gchar *file, *tmpFile, *basename;
  GString *errorMessage, *message;
  gboolean resOk;
  gsize ecrit, lu;
  int lines;

  g_return_if_fail(type == VISU_CONFIGFILE_RESOURCE || type == VISU_CONFIGFILE_PARAMETER);
  g_return_if_fail(saveDialog && entry);

  if (!getFileSystemInUTF8())
    file = g_filename_from_utf8(gtk_entry_get_text(entry), -1, &lu, &ecrit, NULL);
  else
    file = g_strdup(gtk_entry_get_text(entry));
  
  if (g_file_test(file, G_FILE_TEST_IS_DIR))
    {
      tmpFile=
	g_build_filename(file, visuConfigFileGet_defaultFileName(type), NULL);
      g_free(file);
      file = tmpFile;
    }
  
  errorMessage = (GString*)0;
  resOk = visuConfigFileSave(type, file, &errorMessage, &lines);
  if (!resOk)
    {
      if (errorMessage)
	raiseAlertDialogWithScrollView(errorMessage->str);
    }
  if (errorMessage)
    {
      DBG_fprintf(stderr, "Gtk Save : trace from exporting par/res %d ...\n%s",
		  type, errorMessage->str);
      g_string_free(errorMessage, TRUE);
    }
  
  basename = g_path_get_basename(file);
  message = g_string_new("");
  if (resOk)
    g_string_append_printf(message, _("File '%s' succesfully written (%d lines)."),
			   basename, lines);
  else
    g_string_append_printf(message, _("WARNING! File '%s' not written."), basename);
				showAlertMessage(saveDialog, message->str, !resOk, type);
				g_string_free(message, TRUE);
  g_free(basename);

  g_free(file);
}

void showAlertMessage(GtkWidget *saveDialog, gchar* message, gboolean warning, int type)
{
  GtkWidget *wd;

  g_return_if_fail(type == VISU_CONFIGFILE_RESOURCE || type == VISU_CONFIGFILE_PARAMETER);
  g_return_if_fail(saveDialog);

  if (type == VISU_CONFIGFILE_RESOURCE)
    wd = lookup_widget(saveDialog, "imageWarningResources");
  else
    wd = lookup_widget(saveDialog, "imageWarningParameters");
  if (warning)
    gtk_widget_show(wd);
  else
    gtk_widget_hide(wd);

  if (type == VISU_CONFIGFILE_RESOURCE)
    {
      wd = lookup_widget(saveDialog, "statusbarResources");
      gtk_statusbar_pop(GTK_STATUSBAR(wd), saveResourcesContextId);
      gtk_statusbar_push(GTK_STATUSBAR(wd), saveResourcesContextId, message);
    }
  else
    {
      wd = lookup_widget(saveDialog, "statusbarParameters");
      gtk_statusbar_pop(GTK_STATUSBAR(wd), saveParametersContextId);
      gtk_statusbar_push(GTK_STATUSBAR(wd), saveParametersContextId, message);
    }
}

void onTextEntryChange(GtkEditable *entry, gpointer data)
{
  gboolean valid, reParse;
  GtkTreeIter iter;
  GtkListStore *listOfFiles;
  GtkEntryCompletion *completion;
  gchar *dirEntry, *dirBrowsed;
  GDir *gdir;
  const gchar *fileFromDir, *fileEntry;
  gsize ecrit, lu;
  gchar *fileUTF8, *saveFile, *saveFileUTF8;

  fileEntry = gtk_entry_get_text(GTK_ENTRY(entry));
  if (!fileEntry || !fileEntry[0])
    return;

  DBG_fprintf(stderr, "Gtk Save : browse directory to populate the completion.\n");
  completion = gtk_entry_get_completion(GTK_ENTRY(entry));
  g_return_if_fail(completion);

  listOfFiles = GTK_LIST_STORE(gtk_entry_completion_get_model(completion));
  g_return_if_fail(listOfFiles);

  reParse = FALSE;
  if (!lastEntryResources)
    reParse = TRUE;
  else
    {
      dirEntry = g_path_get_dirname(fileEntry);
      DBG_fprintf(stderr, "Gtk Save : current and last directories...\n %s\n %s\n",
		  dirEntry, lastEntryResources);
      if (strcmp(dirEntry, lastEntryResources))
	reParse = TRUE;
      g_free(dirEntry);
    }

  DBG_fprintf(stderr, "Gtk Save : reparse is needed : %d.\n", reParse);

  if (!reParse)
    {
      gtk_entry_completion_complete(completion);
      return;
    }

  gtk_list_store_clear(listOfFiles);
  dirEntry = g_path_get_dirname(fileEntry);
  g_free(lastEntryResources);
  lastEntryResources = dirEntry;
  if (!getFileSystemInUTF8())
    dirBrowsed = g_filename_from_utf8(dirEntry, -1, &lu, &ecrit, NULL);
  else
    dirBrowsed = g_strdup(dirEntry);
  gdir = g_dir_open(dirBrowsed, 0, NULL);
  if (!gdir)
    {
      g_free(dirBrowsed);
      return;
    }
  fileFromDir = g_dir_read_name(gdir);
  while (fileFromDir)
    {
/*       DBG_fprintf(stderr, "Gtk Save : adding '%s' to completion list.\n", fileFromDir); */
      if (!getFileSystemInUTF8())
	{
	  fileUTF8 = g_filename_to_utf8(fileFromDir, -1, &lu, &ecrit, NULL);
	  if (!fileUTF8)
	    g_warning("INTERNAL ERROR! Impossible to convert this file"
		      " name (%s) to UTF8.\n", fileFromDir);
	}
      else
	fileUTF8 = g_strdup(fileFromDir);

      if(fileUTF8)
	{
	  saveFile = g_build_filename(dirBrowsed, fileFromDir, NULL);
	  if (g_file_test(saveFile, G_FILE_TEST_IS_DIR))
	    saveFileUTF8 = g_build_filename(dirEntry, fileUTF8, "/", NULL);
	  else
	    saveFileUTF8 = g_build_filename(dirEntry, fileUTF8, NULL);
	  gtk_list_store_append(listOfFiles, &iter);
	  gtk_list_store_set(listOfFiles, &iter,
			     GTK_SAVE_FILE_NAME, saveFileUTF8,
			     -1);
	  g_free(fileUTF8);
	  g_free(saveFile);
	}
      fileFromDir = g_dir_read_name(gdir);
    }
  g_free(dirBrowsed);
  DBG_fprintf(stderr, "Gtk Save : summiting new list of completion.\n");
  gtk_entry_completion_complete(completion);
}
