/* ***********************IMPORTANT *********************************************
 *  Copyright (C) 2004-2007 Thierry Lagarde <tlagarde@users.sourceforge.net>
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License.
 *
 *
 *                      ********************
 *
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *
 *                      ********************
 *
 *
 * You are highly encouraged to send your changes to <tlagarde@users.sourceforge.net>
 * for possible incorporation into the main distribution.
 * By sending these changes to <tlagarde@users.sourceforge.net>,
 * it is assumed that you are offering <tlagarde@users.sourceforge.net>
 * the unlimited, non-exclusive right to reuse, modify, and relicense the code.
 *
 *
 *                      ********************
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 **************************************************************************************/
#ifdef         __SCRIPT_ENABLE

#include <gtk/gtk.h>
#include "Settings_Script.h"
#include "Settings.h"
#include "Objet_Liste.h"
#include "Interface/Settings_Interface.h"
#include "Debug.h"
#include "Declaration_Constante.h"
#include "Image.h"
#include "main.h"
#include "Macro.h"

void Liste_Script_Efface_Champs (void)
{
	Liste_Script_Modification_Interface = TRUE;
	gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_name), "");
	gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_Params), "");
/*#ifdef  __GNOME_ENABLE
	gnome_icon_entry_set_filename (GNOME_ICON_ENTRY (iconentry_Liste_Scripts), "");
#else

#endif*/
	gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_Path), "");	
	Liste_Script_Modification_Interface = FALSE;
}


void Liste_Script_Sensible (gboolean bool)
{
	gtk_widget_set_sensitive (entry_Liste_Scripts_name, bool);
	gtk_widget_set_sensitive (entry_Liste_Scripts_Path, bool);
	gtk_widget_set_sensitive (button_Liste_Scripts_Path, bool);
	gtk_widget_set_sensitive (entry_Liste_Scripts_Params, bool);

}


void Initialisation_Liste_Script (void)
{
	Liste_Script_Modification_Interface = TRUE;
	Liste_Script_Sensible (FALSE);
	gtk_widget_set_sensitive (button_Liste_Scripts_Add, TRUE);
	gtk_widget_set_sensitive (button_Liste_Scripts_Delete, FALSE);
	gtk_widget_set_sensitive (button_Liste_Scripts_Ok, FALSE);
	gtk_widget_set_sensitive (button_Liste_Scripts_Cancel, FALSE);
	Script_Modification = NULL;
	Script_Selectionner = NULL;
	Liste_Script_Modification_Interface = FALSE;
/*#ifdef  __GNOME_ENABLE
	gnome_icon_entry_set_pixmap_subdir (GNOME_ICON_ENTRY (iconentry_Liste_Scripts), PATH_ICONE "Script/");
#else

#endif*/
}


void Affiche_Script (struct Struct_Liste_Script *Script)
{
	GtkTreeModel *model = NULL;
	GtkTreeIter Ligne;

	ERROR_if (Script == NULL);
	model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview_Liste_Scripts));
	gtk_tree_store_append (GTK_TREE_STORE (model), &Ligne, NULL);
	Script->ID_Arbre_Ligne = Ligne;
	gtk_tree_store_set (GTK_TREE_STORE (model), &Ligne, COL_SCRIPT, Script->Name, COL_PATH, Script->Path, POINTER_SCRIPT, Script, -1);
}


void Afficher_Liste_Script (void)
{
	struct Struct_Liste_Script *Script = NULL;
	guint     Nb_Objet_Liste, i;

	Nb_Objet_Liste = g_list_length (Settings->GList_Script);
	for (i = 0; i < Nb_Objet_Liste; i++) {
		Script = g_list_nth_data (Settings->GList_Script, i);
		Affiche_Script (Script);
	}
}

void Supprime_Script_liste (struct Struct_Liste_Script *Script)
{
	GtkTreeModel *model = NULL;

	ERROR_if (Script == NULL);
	G_LIST_REMOVE (Settings->GList_Script, Script);
	model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview_Liste_Scripts));
	gtk_tree_store_remove (GTK_TREE_STORE (model), &Script->ID_Arbre_Ligne);
	MYFREE (Script->Name);
	MYFREE (Script->Path);
	MYFREE (Script->Param);
	MYFREE (Script->Icon);
	MYFREE (Script);	
}


struct Struct_Liste_Script *Modifie_Ajouter_Script_Dans_Glist (void)
{
	struct Struct_Liste_Script *Script = NULL;

	if (Script_Modification == NULL) {
		MALLOC (Script, sizeof (struct Struct_Liste_Script));
	}
	else
		Script = Script_Modification;

	free_gchar_if_no_null (Script->Name);
	Script->Name = g_strdup (gtk_entry_get_text (GTK_ENTRY (entry_Liste_Scripts_name)));
	if (strlen (Script->Name) != 0) {
		free_gchar_if_no_null (Script->Path);
		Script->Path = g_strdup (gtk_entry_get_text (GTK_ENTRY (entry_Liste_Scripts_Path)));
		free_gchar_if_no_null (Script->Param);
		Script->Param = g_strdup (gtk_entry_get_text (GTK_ENTRY (entry_Liste_Scripts_Params)));
		free_gchar_if_no_null (Script->Icon);
#ifdef  __GNOME_ENABLE
		Script->Icon = gnome_icon_entry_get_filename (GNOME_ICON_ENTRY (iconentry_Liste_Scripts));
#else

#endif
		if (Script->Icon != NULL) {
			Script->icone = Chargement_Image (Script->Icon, COULEUR);
		}
		if (Script_Modification == NULL)
			G_LIST_APPEND (Settings->GList_Script, Script);
	}
	else
		return NULL;
	return Script;	
}


void Modifie_Ajoute_Nouveau_Script (void)
{
	struct Struct_Liste_Script *Script = NULL;
	GtkTreeModel *model = NULL;

	if (Script_Modification != NULL) {
		Modifie_Ajouter_Script_Dans_Glist ();
		model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview_Liste_Scripts));
		gtk_tree_store_set (GTK_TREE_STORE (model), &Script_Modification->ID_Arbre_Ligne, COL_SCRIPT, Script_Modification->Name, COL_PATH, Script_Modification->Path, -1);
		return;
	}
	else {
	
		Script = Modifie_Ajouter_Script_Dans_Glist ();
		if (Script != NULL)
			Affiche_Script (Script);
		else
			debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Nom du Script Vide");
		return;	
	}
}


static void Write_Script_to_xml (xmlNodePtr xmlnode, struct Struct_Liste_Script *Script)
{
	xmlNodePtr newxml = NULL;

	ERROR_if (xmlnode == NULL);
	ERROR_if (Script == NULL);
	newxml = xmlNewChild (xmlnode, NULL, "Script", NULL);
	xmlSetProp (newxml, "Name", Script->Name);
	xmlSetProp (newxml, "Path", Script->Path);
	xmlSetProp (newxml, "Params", Script->Param);
	xmlSetProp (newxml, "Icon", Script->Icon);
}


static gboolean write_xml_file_Subnet (char *fname)
{
	struct Struct_Liste_Script *Script = NULL;
	xmlDocPtr doc = NULL;
	guint     Nb_Objet_Liste, i;
	xmlNode *root_element = NULL;
	
	ERROR_if (fname == NULL);




	
	doc = xmlNewDoc(BAD_CAST "1.0");
    root_element = xmlNewNode(NULL, BAD_CAST "Script_AutoScan");
    xmlDocSetRootElement(doc, root_element);
	
	xmlAddChild (root_element, xmlNewDocComment (doc, "Copyright (c) Lagarde thierry. \nThis Database is available for free use by open source software under the terms of the GNU General Public License.\nContact <tlagarde@users.sourceforge.net>  for more information"));
	/*doc->root = xmlNewDocNode (doc, NULL, "Script_AutoScan", NULL);
	xmlAddChild (doc->root, xmlNewDocComment (doc, "Copyright (c) Lagarde thierry. \nThis Database is available for free use by open source software under the terms of the GNU General Public License.\nContact <tlagarde@user.sourceforge.net>  for more information"));*/
	Nb_Objet_Liste = g_list_length (Settings->GList_Script);
	for (i = 0; i < Nb_Objet_Liste; i++) {
		Script = g_list_nth_data (Settings->GList_Script, i);
		Write_Script_to_xml (root_element, Script);
	}
	if (xmlSaveFile (fname, doc) == -1) {
		xmlFreeDoc (doc);
		debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "impossible d'enregistrer le fichier xml");
		return FALSE;
	}
	xmlFreeDoc (doc);
	return TRUE;
}


void Enregistrement_Donnee_Xml_Script (void)
{
	gchar    *Chemin = NULL;

	Chemin = g_strdup_printf ("%s/.autoscan-network/config/Script.xml", Info_User->pw_dir);
	write_xml_file_Subnet (Chemin);
	MYFREE (Chemin);
}


void Lit_Donnee_Xml_Script (xmlNodePtr xmlnode)
{
	struct Struct_Liste_Script *Script = NULL;

	ERROR_if (xmlnode == NULL);

	if (!xmlnode->name || g_strcasecmp (xmlnode->name, "Script") != 0)
		return;

	MALLOC (Script, sizeof (struct Struct_Liste_Script));

	Script->Name = xmlGetProp (xmlnode, "Name");
	if (Script->Name) {
		Script->Path = xmlGetProp (xmlnode, "Path");
		Script->Param = xmlGetProp (xmlnode, "Params");
		Script->Icon = xmlGetProp (xmlnode, "Icon");
		if ((Script->Icon != NULL) && (strlen (Script->Icon) != 0)) {
			Script->icone = Chargement_Image (Script->Icon, COULEUR);
		}
		G_LIST_APPEND (Settings->GList_Script, Script);
	}
	else {
		MYFREE (Script);
		debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Nom du Script Vide pendant la lecture du fichier xml");
		return;
	}
}



void Lit_Xml_Script (xmlDocPtr doc)
{
	xmlNodePtr node = NULL;
	xmlNode *root_element = NULL;
	
	ERROR_if (doc == NULL);

	root_element = xmlDocGetRootElement(doc);
	for (node = root_element->children; node != NULL; node = node->next) {
		if (node->type == XML_ELEMENT_NODE) 
		Lit_Donnee_Xml_Script (node);
	}
	/*for (node = doc->root->childs; node != NULL; node = node->next) {
		Lit_Donnee_Xml_Script (node);
	}*/
}


gboolean Lit_Xml_Script_Fichier (char *fname)
{
	xmlDocPtr doc = NULL;
	xmlNode *root_element = NULL;
	
	ERROR_if (fname == NULL);
	if (!g_file_test(fname,G_FILE_TEST_EXISTS)) {	

		debug_printf (INTERFACE, D_WARN_USER, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Error loading file : [%s]", fname);
		return FALSE;
	}

	doc = xmlParseFile (fname);
	if (!doc) {
		debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Fichier XML Script : [%s]", fname);
		return FALSE;
	}
	root_element = xmlDocGetRootElement(doc);

	if (!root_element || !root_element->name || g_strcasecmp (root_element->name, "Script_AutoScan") != 0) {
		if (!root_element)
			debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "l'element n'est pas root");
		debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Fichier XML Port mal formaté : [%s]", fname);
		xmlFreeDoc (doc);
		return FALSE;
	}
	/*if (!doc->root || !doc->root->name || g_strcasecmp (doc->root->name, "Script_AutoScan") != 0) {
		if (!doc->root)
			debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "l'element n'est pas root");
		debug_printf (INTERFACE, D_WARN, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Fichier XML Port mal formaté : [%s]", fname);
		xmlFreeDoc (doc);
		return FALSE;
	}*/

	Lit_Xml_Script (doc);

	xmlFreeDoc (doc);
	return TRUE;
}


gboolean Selectionne_Script (GtkWidget * widget, GdkEventButton * event, gpointer user_data)
{
	struct Struct_Liste_Script *Script = NULL;
	GtkTreeModel *model = NULL;
	GtkTreePath *path = NULL;
	GtkTreeIter iter;
	gint      x, y;

	if (event->type == GDK_BUTTON_PRESS) {
		GdkEventButton *bev = (GdkEventButton *) event;

		model = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
		gdk_window_get_pointer (event->window, &x, &y, NULL);
		if (!gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (widget), x, y, &path, NULL, NULL, NULL)) {
			return FALSE;
		}
		gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &iter, path);
		gtk_tree_model_get (model, &iter, POINTER_SCRIPT, &Script, -1);
		switch (bev->button) {
		    case 1:
			    Script_Selectionner = Script;
			    Liste_Script_Efface_Champs ();
			    Liste_Script_Sensible (TRUE);
			    Liste_Script_Modification_Interface = TRUE;
			    gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_name), Script->Name);
			    gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_Path), Script->Path);
			    gtk_entry_set_text (GTK_ENTRY (entry_Liste_Scripts_Params), Script->Param);
			    if (Script->Icon != NULL){
#ifdef  __GNOME_ENABLE
				    gnome_icon_entry_set_filename (GNOME_ICON_ENTRY (iconentry_Liste_Scripts), Script->Icon);
#else

#endif
			    }
			    Liste_Script_Modification_Interface = FALSE;
			    gtk_widget_set_sensitive (button_Liste_Scripts_Add, TRUE);
			    gtk_widget_set_sensitive (button_Liste_Scripts_Delete, TRUE);
			    gtk_widget_set_sensitive (button_Liste_Scripts_Ok, FALSE);
			    gtk_widget_set_sensitive (button_Liste_Scripts_Cancel, FALSE);
			    break;
		    default:
			    debug_printf (INTERFACE, D_INFO, __FILE__, __PRETTY_FUNCTION__, __LINE__, "Pas d'actions pour cette combinaison  (%d)", bev->button);
		}
	}
	return FALSE;
}


gint sort_func_Croissant_Script (GtkTreeModel * model, GtkTreeIter * a, GtkTreeIter * b, gpointer user_data)
{
	gchar    *name_a = NULL, *name_b = NULL;
	int       ret;

	gtk_tree_model_get (model, a, COL_SCRIPT, &name_a, -1);
	gtk_tree_model_get (model, b, COL_SCRIPT, &name_b, -1);
	ret = g_utf8_collate (name_a, name_b);
	MYFREE (name_a);
	MYFREE (name_b);
	return ret;
}


void Create_Liste_Script (void)
{
	GtkTreeModel *model = NULL;
	GtkTreeViewColumn *col = NULL;
	GtkCellRenderer *texte = NULL;
	GtkTreeSelection *selection = NULL;
	GtkTreeStore *store = NULL;

	store = gtk_tree_store_new (NUM_COLS_SCRIPT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);
	gtk_tree_sortable_set_default_sort_func (GTK_TREE_SORTABLE (store), sort_func_Croissant_Script, NULL, NULL);
	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (store), GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING);
	model = GTK_TREE_MODEL (store);
	treeview_Liste_Scripts = gtk_tree_view_new_with_model (model);
	gtk_widget_show (treeview_Liste_Scripts);
	g_object_unref (model);
	gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (treeview_Liste_Scripts), TRUE);
	gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview_Liste_Scripts), TRUE);
	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview_Liste_Scripts));
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);

	col = gtk_tree_view_column_new ();
	gtk_tree_view_column_set_title (col, "Script");
	texte = gtk_cell_renderer_text_new ();
	gtk_tree_view_column_pack_start (col, texte, FALSE);
	gtk_tree_view_column_set_attributes (col, texte, "text", COL_SCRIPT, NULL);

	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview_Liste_Scripts), col);
	col = gtk_tree_view_column_new ();
	gtk_tree_view_column_set_title (col, "Path");
	texte = gtk_cell_renderer_text_new ();
	gtk_tree_view_column_pack_start (col, texte, FALSE);
	gtk_tree_view_column_set_attributes (col, texte, "text", COL_PATH, NULL);
	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview_Liste_Scripts), col);
	g_signal_connect ((gpointer) treeview_Liste_Scripts, "button-press-event", G_CALLBACK (Selectionne_Script), treeview_Liste_Scripts);
}


#endif
