/*
 * Initial main.c file generated by Glade. Edit as required.
 * Glade will not overwrite this file.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

#include "interface.h"
#include "support.h"
#include "status.h"
#include "message.h"
#include "msg_handle.h"
#include "options.h"
#include "dirs.h"
#include "draw.h"
#include "gui.h"
#include "backend.h"
#include "playerlist.h"

#define DEBUG 0
#include "debug.h"


GtkWidget *main_window;

/* gui update */
extern struct s_gui gui;
void update_main_window(void);

static void cleanup(void) {
	option_store_to_default();
	dir_cleanup();
}

static void on_signal(int sig) {
	DBG_MSG(1, "Caught signal %d", sig);
	cleanup();
	exit(0);
}

int
main (int argc, char *argv[])
{
	int opt;
	const char *autorun = NULL;

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	/* gtk initialization */
	gtk_set_locale ();
	gtk_init (&argc, &argv);
	add_pixmap_directory (PACKAGE_DATA_DIR "/" PACKAGE "/pixmaps");

	/* set up default configuration & parse cmd line options */
	option_init();
	while ((opt = getopt(argc, argv, "c:")) != -1) {
		switch(opt) {
			case 'c':
				option_set_string("main", "dir.config_file", optarg);
				break;
			case ':':
				fprintf(stderr, "Option needs value\n");
				exit(1);
				break;
			case '?':
				fprintf(stderr, "Unknown option: %c\n", optopt);
				exit(1);
				break;
		}
	}

	/* register message destinations */
	message_init();
	message_register_target('O', msg_handle_options);
	message_register_target('C', msg_handle_chat);
	message_register_target('N', msg_handle_backend);
	message_register_target('G', msg_handle_backend);
	message_register_target('S', msg_handle_session);
	message_register_target('B', msg_handle_draw);
	message_register_target('P', msg_handle_playerlist);

	/* signal handlers */
	signal(SIGINT, on_signal);
	signal(SIGTERM, on_signal);
	
	/* initialize player list */
	playerlist_init();
	
	/* create main window */
	main_window = create_main_window ();
	after_create_main_window();
	switch_to_status(S_OFFLINE);
	draw_init();

	playerlist_set_update_callback(update_playerlist);

	/* load configuration */
	dir_update();
	option_load_file(dir_main_config);
	dir_update();
	if ((autorun = option_get_string("main", "dir.startup_file")) && autorun[0])
		option_load_file(autorun);
	update_main_window();
	
	/* Go ! */
	gtk_widget_show (main_window);
	show_dialog_connect();
	gtk_main();

	/* Bye */
	cleanup();
	return 0;
}

