/*  GFAX - Gnome fax application
 *  Copyright (C) 1999 George A. Farris
 *
 *  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, or
 *  (at your option) any later version.
 *
 *  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 General Public License for more details.
 *
 *  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.
*/


#include <config.h>
#include <gnome.h>
#include <glade/glade.h>
#include "gfax.h"
#include "phbook.h"

Phbook *book=NULL;

/*=========================================================================
 * Destination *phone_book(Destination *dest)
 *
 *  Called from: "phoneBook" button - gfax.c
 *  Returns    : pointer to destination struct that holds the following:
 				 Organization
				 Fax number
				 Attention
 *
 *	Run the phone book widget.
 *
 *-----------------------------------------------------------------------*/
Destination *phone_book(Destination *dest)
{

	GladeXML *window;				/* The main window */
	
	book = (Phbook*)malloc(sizeof(Phbook));
	book->dest = dest;
	
	window = glade_xml_new(GLADEDIR "/gfax.glade", "phbook");


	/* get the widgets */
	book->closeButton = (GtkButton *)glade_xml_get_widget(window, "closeButton");
	book->deleteBookButton = (GtkButton *)glade_xml_get_widget(window, "deleteBookButton");
	book->addBookButton = (GtkButton *)glade_xml_get_widget(window, "addBookButton");
	book->gnomeCardButton = (GtkButton *)glade_xml_get_widget(window, "gnomeCardButton");
	book->phoneBookCList = (GtkCList *)glade_xml_get_widget(window, "phoneBookCList");
	book->phoneItemCList = (GtkCList *)glade_xml_get_widget(window, "phoneItemCList");
	book->main = (GtkDialog *)glade_xml_get_widget(window, "phbook");
						
	/* connect the signals */		
	glade_xml_signal_connect(window, "on_closeButton_clicked", on_close_clicked);
	glade_xml_signal_connect(window, "on_deleteBookButton_clicked", on_deleteBook_clicked);
	glade_xml_signal_connect(window, "on_addBookButton_clicked", on_addBook_clicked);
	glade_xml_signal_connect(window, "on_gnomeCardButton_clicked", on_gnomeCard_clicked);
	glade_xml_signal_connect(window, "on_phoneBookCList_select_row", select_row);
	glade_xml_signal_connect(window, "on_phoneItemCList_select_row", select_row);
	
	/* clear the lists */
	gtk_clist_clear(book->phoneBookCList);
	gtk_clist_clear(book->phoneItemCList);

	update_phoneBook_CList();

	gtk_window_set_modal(GTK_WINDOW(book->main),0);
	gtk_main();
	gtk_object_destroy(GTK_OBJECT(book->main));
	
	return dest;
}	


static void on_close_clicked(GtkWidget *widget)
{
	gtk_main_quit();
	return;
}
	

static void on_deleteBook_clicked(GtkWidget *widget)
{
/*     void *item_iter = NULL;
    gchar *section_name = NULL; */
	gchar *key, *value;
    GString *tmpstr;
/*  	GString *root; */
    gpointer config_iterator;
    gint count = 0;
    
    tmpstr = g_string_new(NULL);


    /* del the selected phone book in the config file */
    g_string_sprintf(tmpstr, "/Gfax/PhoneBooks/%s", book->currentPhoneBookSelection);
	
    /* Iterate over the phonebook list */
    config_iterator = gnome_config_init_iterator("/Gfax/PhoneBooks");

    /* get the number of phonebooks */
    while ((config_iterator = gnome_config_iterator_next(config_iterator, &key, &value))) {
            count++;
    }
    
    /* This covers a silly bug that seg faults if you sync on the last item
    being removed from a section. */
    if (count == 1) {
            gnome_config_clean_section("/Gfax/PhoneBooks");
    }else {
            gnome_config_clean_key(tmpstr->str);
    }

    gnome_config_sync();            

    g_string_free(tmpstr, TRUE);
    g_free(key);
    g_free(value);
    
	update_phoneBook_CList();   
	gtk_clist_clear(book->phoneItemCList);

	return;
}



/*=========================================================================
 * static void on_addBook_clicked(GtkWidget *widget)()
 *	
 *
 *-----------------------------------------------------------------------*/
static void on_addBook_clicked(GtkWidget *widget)
{

	GladeXML *window;
	
	window = glade_xml_new(GLADEDIR "/gfax.glade", "addphonebook");

	book->addPBWindow = (GtkDialog *)glade_xml_get_widget(window, "addphonebook");
	book->addPBFileEntry = (GnomeFileEntry *)glade_xml_get_widget(window, "addPBFileEntry");
	book->addPBEntry = (GtkEntry *)glade_xml_get_widget(window, "addPBEntry");
		
	glade_xml_signal_connect(window, "on_addPBCancelButton_clicked", on_addPBCancelButton_clicked);
	glade_xml_signal_connect(window, "on_addPBOkButton_clicked", on_addPBOkButton_clicked);
	
	return;
}


static void on_addPBCancelButton_clicked(GtkWidget *button)
{
	gtk_object_destroy((GtkObject *)book->addPBWindow);
	return;
}


static void on_addPBOkButton_clicked(GtkWidget *button)
{	
	GString *tmpstr, *root;
	gchar *ps;


	tmpstr = g_string_new(NULL);
	root = g_string_new(NULL);

	/* get the file path and name */
	ps = g_strdup(gnome_file_entry_get_full_path(book->addPBFileEntry, 0));

	/* add the new phb to the config file */
  	g_string_sprintf(root, "/Gfax/PhoneBooks/%s", gtk_entry_get_text(book->addPBEntry));

 	g_string_sprintf(tmpstr, "%s", ps);

	gnome_config_set_string(root->str, tmpstr->str);
	gnome_config_sync();
		
	g_string_free(tmpstr, TRUE);
	g_string_free(root, TRUE);
	g_free(ps);
	update_phoneBook_CList();
	gtk_object_destroy((GtkObject *)book->addPBWindow);
	
	return;
}




/*=========================================================================
 * static void on_gnomeCard_clicked(GtkWidget *widget)()
 *	
 *
 *-----------------------------------------------------------------------*/
static void on_gnomeCard_clicked(GtkWidget *widget)
{
	system("gnomecard");
	return;
}


/*=========================================================================
 * gint read_vcard_file(gchar *filename)
 * 
 * Read the vcard database that is created with the gnomecard program.	
 * Return 1 if no vcard file exists
 * Return 0 if everything is ok.
 *-----------------------------------------------------------------------*/
static gint read_vcard_file(gchar *filename)
{
	gchar *pLine, *pBeginLine;
	gchar buf[256];
	gchar *text[] = {"", "", ""};		/* template for making new row */
	gchar org[100];
	gchar telfax[100];
	gchar n[100];
	gchar last_name[40], first_name[40];
	gchar *pS;			/* scratch string */
	gint row, i, j;
	gboolean isfaxentry = FALSE;
	FILE *fp;

	if ((fp = fopen(filename, "r")) == NULL) {
		fprintf(stderr, _("Can't open vcard file\n"));
/*
		do_message(_("\nCan't open vcard file.\n\
					\nYou need to run GnomeCard to create phone books.\n"));
		return(1);
*/
	}

	pBeginLine = (gchar *)g_malloc(256);

	gtk_clist_clear(book->phoneItemCList);	/* clear the list before we do anything */
 	gtk_clist_freeze(book->phoneItemCList);	/* put them in the CList */
	
	while (fgets(buf, 254, fp) != NULL) {
		if (strncmp(buf, "BEGIN:VCARD", 11) == 0) {
			/* begin vcard */

			while (strncmp(buf, "END:VCARD", 9) != 0)  {	/* do it until end of entry */
				/* get next line */
				fgets(buf, 98, fp);		/* only allow 98 chars */
				pLine = pBeginLine;		/* point to beginning of line */
				
				/* strip all the \r and \n */
				for (i = 0; buf[i] != '\0'; i++) {
					if (buf[i] == '\r' || buf[i] == '\n') {
						continue;
					}
					*pLine++ = buf[i];
				}
				*pLine = '\0';	/* terminate the line */
		
				pLine = pBeginLine;		/* point to beginning again */
				/* get the organization */
				if (strncmp(pLine, "ORG:", 4) == 0) {
					strncpy(org, &pLine[4], 90);
					continue;
				}
				/* get the fax number */
				if (strncmp(pLine, "TEL;FAX:", 8) == 0) {
					strncpy(telfax, &pLine[8], 90);
					isfaxentry = TRUE;
					continue;
				}
				/* get the person name (attention) */
				if (strncmp(pLine, "N:", 2) == 0) {
					/* nock off the N: */
					pS = pLine + 2;	
					/* get last name */
					for (i = 0; pS[i] != ';'; i++)
						last_name[i] = pS[i];
					last_name[i++] = '\0';
					/* get first name */
					for (j = 0; pS[i] != ';' && pS[i] != '\0'; i++, j++) {
						first_name[j] = pS[i];
					}
					first_name[j++] = '\0';
									
					g_snprintf(n, 90, "%s %s", first_name,last_name);
					continue;
				}
			}/* end vcard */
			
			/* only put entries in that have fax numbers */
			if (isfaxentry) {
				row = gtk_clist_append(book->phoneItemCList, (gchar **)text);	/* make new row */
				if (org)
					gtk_clist_set_text(book->phoneItemCList,row,0,org);									
				if (telfax)
					gtk_clist_set_text(book->phoneItemCList,row,1,telfax);
				if (n)
					gtk_clist_set_text(book->phoneItemCList,row,2,n);
				isfaxentry = FALSE;
			}
			
			for (i=0; i <100; i++) {	/* zero these */
				org[i] = '\0';
				telfax[i] = '\0';
				n[i] = '\0';
			}
			
		}/* end if BEGIN:VCARD */
			
	}

	gtk_clist_thaw(book->phoneItemCList);
	
	g_free(pBeginLine);
	fclose(fp);
	
	return(0);
}

 /*=========================================================================
  * static void update_PhoneBookCList(void)
  *
  *	Read phone book list ---------------------------------------------
  *	Phone book entry looks like so:
  *	[PhoneBooks]
  *	Main=/home/george/.gnome/GnomeCard.gcrd
  *	
  * Put the new phone book in the list box
  *-----------------------------------------------------------------------*/
static void update_phoneBook_CList(void)
{

	gchar *phb[] = {""};
	gint row;
	gpointer config_iterator;

	/* clear list */
	gtk_clist_clear(book->phoneBookCList);

	/* Iterate over the phonebook list and store in phonebooklist */
	config_iterator = gnome_config_init_iterator("/Gfax/PhoneBooks");

	if (config_iterator != 0)
    {
    	gchar *key = NULL;
		gchar *value = NULL;
      
    	while ((config_iterator = gnome_config_iterator_next(config_iterator, &key, &value))) 
		{
			/* shouldn't happen, but I'm paranoid */
			if (key == 0 || value == 0)
			{
				if (key) g_free(key);
				if (value) g_free(value);
				continue;
			}
			
			row = gtk_clist_append(book->phoneBookCList, (gchar **)phb);	/* make new row */
			gtk_clist_set_text(book->phoneBookCList, row, 0, key);
  
        }

		g_free(key); key = 0;
		g_free(value); value = 0;
    }

}

/* for the "get" functions, any of the return pointer can be
 * NULL if you are not interested
 */
/* gint gtk_clist_get_text (GtkCList  *clist,
                         gint       row,
                         gint       column,
                         gchar    **text);
 */

static void select_row(GtkCList *clist, gint row, gint col, GdkEvent *event)
{

 	GString *tmpstr, *fn, *text;
	gchar *s;

	tmpstr = g_string_new(NULL);
	fn = g_string_new(NULL);
	text = g_string_new(NULL);

	s = text->str;	/* save this pointer so it doesn't corrupt the list */

	/* if we click on a phone book we load the file in the Item list */
 	if (clist == book->phoneBookCList) {

		gtk_clist_get_text(book->phoneBookCList, row, col, &text->str);
		
		g_string_sprintf(tmpstr, "/Gfax/PhoneBooks/%s", text->str);
		g_string_sprintf(fn, gnome_config_get_string(tmpstr->str));
		
		/* get the phone book name */
 		book->currentPhoneBookSelection = g_strdup(text->str);

	 	if (read_vcard_file(fn->str)) { 
			/* do nothing right now */
 		}
		
		text->str = s;	/* restore the pointer */
	}

	/* go here if we double click in the Item list */
	if (clist == book->phoneItemCList) {
		/* get the name */
		gtk_clist_get_text(book->phoneItemCList, row, 0, &text->str);
		book->dest->organization = g_strdup(text->str);
		text->str = s;
		/* get the number */
		gtk_clist_get_text(book->phoneItemCList, row, 1, &text->str);
		book->dest->faxNumber = g_strdup(text->str);
		text->str = s;
		/* get the attention to */
		gtk_clist_get_text(book->phoneItemCList, row, 2, &text->str);
		book->dest->attention = g_strdup(text->str);
		text->str = s;

		/* if it's a double click then exit like the "Close" button */
		if (event && event->type == GDK_2BUTTON_PRESS) {
	 	   	gtk_main_quit();
		}
	}

	g_string_free(tmpstr, TRUE);
	g_string_free(fn, TRUE);
	g_string_free(text, TRUE);

}
