/*  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 <time.h>
#include <gnome.h>
#include <glade/glade.h>
#include "gfax.h"

int main(int argc,char *argv[]);
static void sendNow_toggled(GtkCheckButton *button);
static void resolution_toggled(GtkCheckButton *button);
static void toggle_ampm(GtkWidget *widget);
static void phone_book_cb(GtkButton *widget);
static void about(GtkWidget *widget);
static void quit(GtkButton *widget);
static void send(GtkButton *button);
static void gfax_setup(GtkWidget *widget);
static void help(GtkWidget *widget, gpointer data);
void showSpoolDialog(void);

Destination *dest=NULL;

GtkEntry *faxNumberEntry;
GtkEntry *nameEntry;
GtkEntry *attentionEntry;
GtkEntry *prefixEntry;
GtkCheckButton *sendNowCheckButton;
GtkCheckButton *resolutionCheckButton;
GnomeAppBar *statusline;

/* Command line processing stuff */
gboolean testMode = FALSE;		/* test mode command line switch */
poptContext ctx;
gchar **args;			/* leftover command line args */

/* ID for Drag-And-Drop */
#define TARGET_URL 1056

static struct poptOption options[] = {
	{"test", 't', POPT_ARG_NONE, &testMode, 0, 
	 N_("Enable test mode"), NULL},
	{NULL, '\0', 0, NULL, 0	}
};

/* these types are accepted by Drag-and-Drop (DND): */
static GtkTargetEntry drag_types[] =
{
	{ "_NETSCAPE_URL", 0, TARGET_URL }
};
static gint n_drag_types = sizeof(drag_types)/sizeof(drag_types[0]);


static void process_one_filename (char *filename)
{
	if ( strncmp(filename, "file:", 5) == 0 ) {
		/* get the file name. We put a \ on the front as an
		   easy way to return a flag to gfax that this file
		   shouldn't be deleted. */

		fileName = g_strdup_printf("\\%s", filename + 5);
	}
}

static void filenames_dropped(GtkWidget * widget,
			      GdkDragContext   *context,
			      gint              x,
			      gint              y,
			      GtkSelectionData *selection_data,
			      guint             info,
			      guint             time)
{
        if (!selection_data->data)
                return;

        switch (info){
        case TARGET_URL:
                process_one_filename ((char *)selection_data->data);
                break;
        }
}

int main(int argc,char *argv[]) {

	gchar dateString[100], hour[3], minute[3];/* , ampm[3]; */
	FILE *fp;
	
	gchar hour24[3];
	time_t the_time;
	struct tm *tm_ptr;
	
	GladeXML *window;				/* The main window */
	GtkWidget *gfax_top_window;
	GtkLabel *dateLabel;			/* The date label */
	GtkOptionMenu *ampmOptionMenu;
	GtkOptionMenu *aboutMenu;
	GtkSpinButton *hourSpinButton;		/* The hour entry */
	GtkSpinButton *minuteSpinButton;	/* The minute entry */

	transmitAgent = NULL;
	emailAddress = NULL;
	phonePrefix = NULL; 
	ourFaxNumber = NULL;
	fileName = NULL;	

	/* setup a single destination */
	dest = (Destination*)malloc(sizeof(Destination));
	
	bindtextdomain (PACKAGE, PACKAGE_LOCALE_DIR);
	textdomain (PACKAGE);


	/* lets get the time */
	(void)time(&the_time);
	tm_ptr = localtime(&the_time);
    
    /* lets get times and dates in ascii */
    strftime(dateString, 100, _("%A %B %d, %Y"), tm_ptr); /* date */
    strftime(hour, 3, "%I", tm_ptr);        /* hour */
    strftime(minute, 3, "%M", tm_ptr);      /* minute */
    strftime(hour24, 3, "%H", tm_ptr);      /* am or pm */
    
    /* ampm is AM if = 0, PM if = 1 */
	if (atoi(hour24) > 12 && atoi(hour24) <= 23)
            ampm = 1;
    else if (atoi(hour24) == 0)
            ampm = 1;
	else if (atoi(hour24) == 12 && (atoi(minute) > 0))
			ampm = 0;
    else
            ampm = 0;
			

	gnome_init_with_popt_table(PACKAGE, VERSION, argc, argv, options, 0 , &ctx);	/* gnome initialization */

	/* get the left over command line arg (fileName) */
	args = (gchar **)poptGetArgs(ctx);
	
	if(args != NULL) {
 		fileName = g_strdup(args[0]);
		if ((fp = fopen(fileName, "r")) == NULL) {
			gchar *message = g_strdup_printf(_("\nFilename -> %s\nDoesn't exist or can't open!\n"), fileName);
			do_message(message);
			g_free(message);
		} else {
			fclose(fp);
		}
	}
	poptFreeContext(ctx);
	
	glade_gnome_init();			/* libglade initialization */
	get_config(CALL_FROM_MAIN);	/* read saved settings */
	dest->deleteFile = TRUE;	/* delete the file unless it's from the fax file dialog */	

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

	/* enable drag-and-drop (DND) */
	gfax_top_window = (GtkWidget *)glade_xml_get_widget(window, "gfax");

	gtk_drag_dest_set (GTK_WIDGET(gfax_top_window),
			   GTK_DEST_DEFAULT_MOTION |
			   GTK_DEST_DEFAULT_HIGHLIGHT |
			   GTK_DEST_DEFAULT_DROP,
			   drag_types, n_drag_types,
			   GDK_ACTION_COPY);

	gtk_signal_connect(GTK_OBJECT(gfax_top_window), "drag_data_received",
			   GTK_SIGNAL_FUNC(filenames_dropped), NULL);

	/* Get all the widgets we'll require  */
	dateLabel = (GtkLabel *)glade_xml_get_widget(window, "dateLabel");
	hourSpinButton = (GtkSpinButton *)glade_xml_get_widget(window, "hourSpinButton");
	minuteSpinButton  = (GtkSpinButton *)glade_xml_get_widget(window, "minuteSpinButton");
	ampmOptionMenu = (GtkOptionMenu *)glade_xml_get_widget(window, "ampmOptionMenu");
	sendNowCheckButton = (GtkCheckButton *)glade_xml_get_widget(window, "sendNowCheckButton");
	resolutionCheckButton = (GtkCheckButton *)glade_xml_get_widget(window, "resolutionCheckButton"); 
	faxNumberEntry = (GtkEntry *)glade_xml_get_widget(window, "fax_numberEntry");
	nameEntry = (GtkEntry *)glade_xml_get_widget(window, "nameEntry");
	attentionEntry = (GtkEntry *)glade_xml_get_widget(window, "attentionEntry");
	prefixEntry = (GtkEntry *)glade_xml_get_widget(window, "prefixEntry");
	aboutMenu = (GtkOptionMenu *)glade_xml_get_widget(window, "aboutMenu");
	statusline = (GnomeAppBar *)glade_xml_get_widget(window, "appbar");

	/* connect any signals we need */
	glade_xml_signal_connect(window, "on_sendFaxButton_clicked", send);
	glade_xml_signal_connect(window, "on_phoneBookButton_clicked", phone_book_cb);
 	glade_xml_signal_connect(window, "on_faxFileButton_clicked", fax_file);
	glade_xml_signal_connect(window, "on_spoolButton_clicked", showSpoolDialog);	
	glade_xml_signal_connect(window, "on_setupButton_clicked", gfax_setup);
	glade_xml_signal_connect(window, "on_exitButton_clicked", quit);
	glade_xml_signal_connect(window, "on_exitMenu_activate", quit);
	glade_xml_signal_connect(window, "on_ampmOptionMenu_clicked", toggle_ampm);
	glade_xml_signal_connect(window, "on_sendNowCheckButton_toggled", sendNow_toggled);
	glade_xml_signal_connect(window, "on_resolutionCheckButton_toggled", resolution_toggled);
	glade_xml_signal_connect(window, "on_aboutMenu_activate", about);
 	glade_xml_signal_connect(window, "on_manualMenu_activate", help);


	/* set the staus line with the current transmit agent */
	if (g_strcasecmp(transmitAgent, "hylafax") == 0) {
		gnome_appbar_set_status(GNOME_APPBAR(statusline), 
					g_strconcat("Transmit Agent :  ", transmitAgent, " on ", hylafaxServerName, NULL));
	}
	
	if (g_strcasecmp(transmitAgent, "mgetty") == 0) {
		gnome_appbar_set_status(GNOME_APPBAR(statusline), 
					g_strconcat("Transmit Agent :  ", transmitAgent, NULL));
	}
	
	
	/* Set the date in the label */
	gtk_label_set(GTK_LABEL(dateLabel), dateString);
	
	/* Set the time in the spinbuttons */
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(hourSpinButton), atoi(hour));
	gtk_spin_button_set_value(GTK_SPIN_BUTTON(minuteSpinButton), atoi(minute));
	
	/* Set the ampm menu to the correct value */
	gtk_option_menu_set_history(GTK_OPTION_MENU(ampmOptionMenu), ampm);

	/* Set the check buttons to saved settings */
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sendNowCheckButton), sendNow_state);
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolutionCheckButton), resolution_state);

	gtk_entry_set_text(GTK_ENTRY(prefixEntry), phonePrefix);	
	
	gtk_main();

	return(0);
}

static void sendNow_toggled(GtkCheckButton *button)
{
	sendNow_state = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
	return;	
}

/* Change between normal and fine resolution */
static void resolution_toggled(GtkCheckButton *button)
{
	resolution_state = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
	return;	
}

static void toggle_ampm(GtkWidget *widget)
{
		if (ampm == 0)
			ampm = 1;
		else
			ampm = 0;
}


/*=========================================================================
 * static void phone_book(GtkButton *widget)
 *
 *  *widget    : The "PhoneBook" button on the main window
 *  Called from: "PhoneBook" button main() - gfax.c
 *  Returns    : void
 *
 *	Run the phonebook dialog
 *
 *-----------------------------------------------------------------------*/
static void phone_book_cb(GtkButton *widget)
{
	dest = phone_book(dest);

	gtk_entry_set_text(GTK_ENTRY(nameEntry), dest->organization);
 	gtk_entry_set_text(GTK_ENTRY(faxNumberEntry), dest->faxNumber);
	gtk_entry_set_text(GTK_ENTRY(attentionEntry), dest->attention);

	return;
}


/*=========================================================================
 * static void send(GtkButton *widget)
 *
 *  *widget    : The "Send Fax" button on the main window
 *  Called from: "Send Fax" button main() - gfax.c
 *  Returns    : void
 *
 *	Run the calls send_fax(dest testMode) to actaully send the fax
 *
 *-----------------------------------------------------------------------*/
static void send(GtkButton *button)
{
	gint error;

	dest->organization = gtk_entry_get_text(GTK_ENTRY(nameEntry));
 	dest->faxNumber = gtk_entry_get_text(GTK_ENTRY(faxNumberEntry));
	dest->attention = gtk_entry_get_text(GTK_ENTRY(attentionEntry));

	if (phonePrefix == NULL)
		phonePrefix = gtk_entry_get_text(GTK_ENTRY(prefixEntry));

	if (fileName == NULL ) {
		do_message(_("No file to fax"));
	} else {
		if (fileName[0] == '\\') {
			dest->deleteFile = FALSE;
			dest->fileName = g_strdup((gchar *)fileName+1);	
		} else {
			dest->fileName = g_strdup(fileName);
		}
	
		error = send_fax(dest, testMode);
		switch (error) {

			case NO_EMAIL_ADDRESS:
				do_message(_("\nYou have email notification set but haven't\nset your email address!\n"));
				return;
			
			case NO_FAX_NUMBER:
				do_message(_("\nYou appear not to have a destination fax number set!\n"));
				return;
	 	}
		gtk_main_quit();
	}
	return;
}


static void gfax_setup(GtkWidget *widget)
{
	if (setup() == CHANGED) {
		/* Set the check buttons to saved settings */
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sendNowCheckButton), sendNow_state);
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(resolutionCheckButton), resolution_state);
		gtk_widget_draw(GTK_WIDGET(gtk_widget_get_toplevel(GTK_WIDGET(widget))), NULL);

		/* set the staus line with the current transmit agent */
		gnome_appbar_set_status(GNOME_APPBAR(statusline), 
			g_strconcat("Transmit Agent :  ", transmitAgent, NULL));
		
	}
	return;
}


static void about(GtkWidget *widget)
{
	GladeXML *window;				/* The main window */
	
	window = glade_xml_new(GLADEDIR "/gfax.glade", "about");
	return;

}

static void help(GtkWidget *widget, gpointer data)
{
	gchar *helpfile;
	
	helpfile = gnome_help_file_find_file("gfax", "gfax.html");
	
	if (helpfile != NULL) {
		gchar *url;
		
		url = g_strconcat("file:", helpfile, NULL);
		gnome_help_goto(NULL, url);
		
		g_free(url);
		g_free(helpfile);
	} else {
		gnome_error_dialog(_("Couldn't find the Gfax manual!"));
	}

	return;
}

/* signal sent when Quit button is clicked */
static void quit(GtkButton *widget) {

	if (dest->deleteFile)	/* we use this if faxing a file, we don't want to delete it */
		if (fileName != NULL)
			if (remove(fileName))
				fprintf(stderr, "Error removing %s\n", fileName);
	
	gtk_main_quit();                      /* the end.*/
}


void do_message(gchar *msg)
{
        GtkWidget *msgbox = gnome_message_box_new(msg,
                        GNOME_MESSAGE_BOX_WARNING, 
						GNOME_STOCK_BUTTON_OK,
						NULL);
						
		gtk_widget_show(msgbox);
		gnome_dialog_run(GNOME_DIALOG(msgbox));
		return;
}

/* These are Emacs variables to use a common "Gfax" coding style:
 * ;;; Local Variables: ***
 * ;;; mode:C ***
 * ;;; c-basic-offset:8 ***
 * ;;; indent-tabs-mode:t ***
 * ;;; End: ***
 */


