
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <glib.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>

#include "gui.h"
#include "interface.h"
#include "callbacks.h"
#include "support.h"
#include "status.h"
#include "options.h"
#include "playerlist.h"
#include "backend.h"

#define DEBUG 		0
#include "debug.h"
#include "utils.h"

struct s_gui gui = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

/* from interfaces.c */
#define GLADE_HOOKUP_OBJECT(component,widget,name) \
  g_object_set_data_full (G_OBJECT (component), name, \
    gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref)


static GtkTreeViewColumn *player_list_column[6];

/*****************************************************************************
 * 	GUI Functions
 ****************************************************************************/

void update_main_window(void) {
	const char *str = NULL;
	int i;
	
	/* menu network */
	gtk_widget_set_sensitive(lookup_widget(main_window, "network_connect"),
			backend_network == NULL);
	gtk_widget_set_sensitive(lookup_widget(main_window, "network_disconnect"),
			backend_network != NULL);

	/* ikonka spojeni */
	gtk_image_set_from_stock(GTK_IMAGE(lookup_widget(main_window, "statusbar_connect")),
			gui.is_online ? "gtk-connect":"gtk-disconnect",
			GTK_ICON_SIZE_MENU);

	/* connection frame */
	if (backend_network) {
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "connection_backend_value_label")),
				option_get_string("main", "net.backend"));
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "connection_address_value_label")),
				option_get_string("main", "net.address"));
		gtk_widget_show(lookup_widget(main_window, "connection_table"));
		gtk_widget_hide(lookup_widget(main_window, "connection_connect_button"));
	} else {
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "connection_backend_value_label")), "");
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "connection_address_value_label")), "");
		gtk_widget_hide(lookup_widget(main_window, "connection_table"));
		gtk_widget_show(lookup_widget(main_window, "connection_connect_button"));
	}
	
	/* chat */
	gtk_widget_set_sensitive(lookup_widget(main_window, "chat_label2"),
			gui.is_online);
	gtk_widget_set_sensitive(lookup_widget(main_window, "chat_entry"),
			gui.is_online);

	/* seznam hracu + nastaveni hry */
	gtk_widget_set_sensitive(lookup_widget(main_window, "players_frame"), gui.is_online);
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_frame"), gui.is_online);
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_name_button"), gui.can_select_game);
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_role_combobox"), gui.can_select_role);
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_start_button"), gui.can_start_game);
	//gtk_widget_set_sensitive(lookup_widget(main_window, "game_end_button"), gui.can_end_game);
	
	if ((str = option_get_string("main", "game.backend"))) {
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "game_name_button_label")), str);
	} else {
		gtk_label_set_text(GTK_LABEL(lookup_widget(main_window, "game_name_button_label")), "--");
	}
	

	
	/* menu hra */
	/* lock */
	gtk_widget_set_sensitive(lookup_widget(main_window, "players_lock_togglebutton"),
			0 && gui.is_online && gui.is_game);
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(lookup_widget(main_window, "players_lock_togglebutton")),
			0 && gui.is_locked);
	//gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_lock_togglebutton")),
	//		0 && gui.is_locked);
	if (gui.is_locked) {
		gtk_widget_show(lookup_widget(main_window, "statusbar_lock_eventbox"));
	} else {
		gtk_widget_hide(lookup_widget(main_window, "statusbar_lock_eventbox"));
	}
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_terminate"), backend_game != NULL);

	/* select */
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_select"),
			gui.can_select_game);
	/* restart */
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_start"),
			gui.can_start_game);
	/* surender */
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_surrender"),
			gui.can_end_game);

	/* pause */
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_pause"), gui.is_game);
	//gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "game_pause")),
	//		0 && gui.is_paused);
	if (gui.is_paused) {
		gtk_widget_show(lookup_widget(main_window, "statusbar_pause_eventbox"));
	} else {
		gtk_widget_hide(lookup_widget(main_window, "statusbar_pause_eventbox"));
	}

	
	/* menu test */
	gtk_widget_set_sensitive(lookup_widget(main_window, "test_draw"),
			!gui.is_online);
	gtk_widget_set_sensitive(lookup_widget(main_window, "test_clean"),
			!gui.is_online);

	set_semaphore(-1);

	/* player list columns */
	i = 0;
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_ack"));
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_nick"));
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_address"));
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_role"));
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_score"));
	gtk_tree_view_column_set_visible(player_list_column[i++], option_get_integer("main", "ui.pl_col_connection"));
	
	/* update menu */
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_ack")),
			option_get_integer("main", "ui.pl_col_ack"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_nick")),
			option_get_integer("main", "ui.pl_col_nick"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_address")),
			option_get_integer("main", "ui.pl_col_address"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_role")),
			option_get_integer("main", "ui.pl_col_role"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_score")),
			option_get_integer("main", "ui.pl_col_score"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "players_column_connection")),
			option_get_integer("main", "ui.pl_col_connection"));
	
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "pref_autoswitch")),
			option_get_integer("main", "ui.autoswitch"));
	gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "pref_showlogs")),
			option_get_integer("main", "ui.show_logs"));
}

void set_semaphore(int x) {
	if (x != -1)
		gui.semafor = x;
	
	/* semafor */
	gtk_widget_set_sensitive(lookup_widget(main_window, "statusbar_turn_no"), gui.semafor & 1);
	gtk_widget_set_sensitive(lookup_widget(main_window, "statusbar_turn_yes"), gui.semafor & 2);
}

void after_create_main_window(void) {
	GtkWidget *wid;
	GtkSizeGroup *size_group;
	GtkWidget *mnu, *mnu_item;
	int i;

	GtkCellRenderer *renderer;
	GtkTreeViewColumn *column;
	GtkTreeView *treeview;

	gchar *widget_names[] = {
		"game_start_button",
		"players_btn_vbox",
		NULL
	};

	DBG_MSG(3, "after_create_main_window");
	
	size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);
	
	for (i = 0; widget_names[i]; i++) {
		wid = lookup_widget(main_window, widget_names[i]);
		gtk_size_group_add_widget (size_group, wid);
	}
	
	gtk_size_group_set_mode (size_group, GTK_SIZE_GROUP_HORIZONTAL);

	DBG_MSG(5, "after_create_main_window: player list");

	/*** prepare player list ***/
	treeview = GTK_TREE_VIEW(lookup_widget(main_window, "players_treeview"));
	i = 0;

	mnu = gtk_menu_new ();
	gtk_menu_item_set_submenu (GTK_MENU_ITEM (lookup_widget(main_window, "mnu_players_columns")), mnu);
	gtk_widget_show (mnu);
	
	/* column: option ack */
	DBG_MSG(5, "after_create_main_window: player list: nick");
	renderer = gtk_cell_renderer_pixbuf_new ();
	g_object_set(renderer, "stock-size", GTK_ICON_SIZE_MENU, NULL);
	column = gtk_tree_view_column_new_with_attributes (_("Ack"), renderer, "stock-id", 0, NULL);
	gtk_tree_view_column_set_resizable (column, FALSE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 0);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("_Ack"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_ack");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_ack");

	/* column: option nick */
	DBG_MSG(5, "after_create_main_window: player list: nick");
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Přezdívka"), renderer, "text", 1, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 1);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("_Přezdívka"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_nick");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_nick");

	/* column: option address */
	DBG_MSG(5, "after_create_main_window: player list: address");
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Adresa"), renderer, "text", 2, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 2);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("A_dresa"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_address");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_address");

	/* column: option role */
	DBG_MSG(5, "after_create_main_window: player list: role");
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Role"), renderer, "text", 3, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 3);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("_Role"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_role");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_role");
	
	/* column: option score */
	DBG_MSG(5, "after_create_main_window: player list: score");
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Skóre"), renderer, "text", 4, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 4);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("_Skóre"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_score");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_score");
	
	/* column: option conn_stat */
	DBG_MSG(5, "after_create_main_window: player list: conn_stat");
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Spojení"), renderer, "text", 5, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 5);
	player_list_column[i++] = column;

	mnu_item = gtk_check_menu_item_new_with_mnemonic (_("Sp_ojení"));
	gtk_container_add (GTK_CONTAINER (mnu), mnu_item);
	gtk_widget_show (mnu_item);
	g_signal_connect ((gpointer) mnu_item, "activate", G_CALLBACK (on_players_columns_activate), "ui.pl_col_connection");
	GLADE_HOOKUP_OBJECT (main_window, mnu_item, "players_column_connection");

	update_playerlist();
}

void enable_board(void) {
	gtk_widget_set_sensitive(lookup_widget(main_window, "desk_drawingarea"), TRUE);
}

void disable_board(void) {
	gtk_widget_set_sensitive(lookup_widget(main_window, "desk_drawingarea"), FALSE);
}

static void append_text_to (GtkWidget *text_view, char* text) {
	GtkTextIter iter;
	GtkTextBuffer *buf;
	GtkTextMark *mark;

	assert(text_view != NULL);
	assert(text != NULL);
	
	buf = gtk_text_view_get_buffer (GTK_TEXT_VIEW(text_view));
	
	gtk_text_buffer_get_end_iter (buf, &iter);
	gtk_text_buffer_insert(buf, &iter, text, -1);
	
	/* scroll down */
	gtk_text_buffer_place_cursor(buf, &iter);
	mark = gtk_text_buffer_get_insert(buf);
	gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(text_view), mark, 0.0, FALSE, 0.0, 1.0);
}

void erase_logs (void) {
	gtk_text_buffer_set_text(gtk_text_view_get_buffer (GTK_TEXT_VIEW(lookup_widget(main_window, "gamelog_textview"))), "", -1);
	gtk_text_buffer_set_text(gtk_text_view_get_buffer (GTK_TEXT_VIEW(lookup_widget(main_window, "netlog_textview"))), "", -1);
}

void append_to_chat(char *fmt, ...) {
	static GtkWidget *tv = NULL, *nb = NULL, *li = NULL;
	va_list ap;
	char *m;
	static int cached_nl = 0;
	int l;

	assert(fmt != NULL);

	if (!tv) tv = lookup_widget(main_window, "chat_textview");
	if (!nb) nb = lookup_widget(main_window, "main_notebook");
	if (!li) li = lookup_widget(main_window, "chat_label_image");

	va_start(ap, fmt);
	if ((m = make_message(fmt, ap))) {
		l = strlen(m);
		if (cached_nl) {
			append_text_to(tv, "\n");
			cached_nl = 0;
		}
		if (l > 0 && m[l - 1] == '\n') {
			cached_nl = 1;
			m[l - 1] = 0;
		}
		append_text_to(tv, m);
	}
	free(m);
	va_end(ap);
	
	/* show alert icon */
	if (GUI_PAGE_CHAT != gtk_notebook_get_current_page(GTK_NOTEBOOK(nb))) {
		gtk_widget_show(li);
	}
}

void append_to_netlog(char *fmt, ...) {
	static GtkWidget *tv = NULL;
	va_list ap;
	char *m;

	assert(fmt != NULL);

	if (!tv) tv = lookup_widget(main_window, "netlog_textview");

	va_start(ap, fmt);
	if ((m = make_message(fmt, ap))) {
		append_text_to(tv, m);
	}
	free(m);
	va_end(ap);
}

void append_to_gamelog(char *fmt, ...) {
	static GtkWidget *tv = NULL;
	va_list ap;
	char *m;

	assert(fmt != NULL);

	if (!tv) tv = lookup_widget(main_window, "gamelog_textview");

	va_start(ap, fmt);
	if ((m = make_message(fmt, ap))) {
		append_text_to(tv, m);
	}
	free(m);
	va_end(ap);
}


void set_statusbar_clock(int is_visible, int set_icon, gchar *fmt,...) {
	va_list ap;
	char *m;
	static GtkWidget *sl;
	static const char *icon_name[GUI_ICON_MAX + 1] = {
		"",
		"statusbar_image_tip",
		"statusbar_image_info",
		"statusbar_image_question",
		"statusbar_image_warning",
		"statusbar_image_error",
		NULL
	};
	static GtkWidget *icon[GUI_ICON_MAX];
	static int active_icon = 0;
	int i;
	
	if (!sl) {
		sl = lookup_widget(main_window, "statusbar_clock_label");
		for (i = 0; i < GUI_ICON_MAX; i++) {
			if (icon_name[i] && icon_name[i][0])
				icon[i] = lookup_widget(main_window, icon_name[i]);
			else
				icon[i] = NULL;
		}
	}
	
	if (set_icon < GUI_ICON_MAX && set_icon >= 0) {
		if (icon[active_icon])
			gtk_widget_hide(icon[active_icon]);
		if (icon[set_icon])
			gtk_widget_show(icon[set_icon]);
		active_icon = set_icon;
	}

	if (is_visible)
		gtk_widget_show(sl);
	else
		gtk_widget_hide(sl);
	
	if (fmt) {
		va_start(ap, (char *) fmt);
		if ((m = make_message((char *) fmt, ap))) {
			gtk_label_set_text(GTK_LABEL(sl), m);
		}
		va_end(ap);
		free(m);
	}
}


void set_statusbar_text(gchar *fmt,...) {
	va_list ap;
	char *m;
	static GtkLabel *sl = NULL;

	DBG_MSG(3, "set_statusbar_text");
	if (!sl) {
		sl = GTK_LABEL(lookup_widget(main_window, "statusbar_label"));
	}

	if (fmt) {
		va_start(ap, (char *) fmt);
		if ((m = make_message((char *) fmt, ap))) {
			gtk_label_set_text(sl, m);
		}
		va_end(ap);
		free(m);
	} else {
		gtk_label_set_text(sl, "");
	}
}

void set_statusbar_progress(int visible, gdouble fraction, gchar *fmt,...) {
	va_list ap;
	char *m;
	static GtkWidget *sp;
	
	if (!sp) sp = lookup_widget(main_window, "statusbar_progressbar");
	
	if (visible)
		gtk_widget_show(sp);
	else
		gtk_widget_hide(sp);

	if (fraction > 1.0)
		fraction = 1.0;
	if (fraction < 0.0)
		fraction = 0.0;
	
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(sp), fraction);
	
	if (fmt) {
		va_start(ap, (char *) fmt);
		if ((m = make_message((char *) fmt, ap))) {
			gtk_progress_bar_set_text(GTK_PROGRESS_BAR(sp), m);
		}
		va_end(ap);
		free(m);
	} else {
		gtk_progress_bar_set_text(GTK_PROGRESS_BAR(sp), "");
	}
}

void show_dialog_connect(void) {
	GDir *dir;
	gchar *dir_name;
	GtkComboBox *dir_combo;
	const char *dir_network = option_get_string("main", "dir.network");
	const char *last_backend = option_get_string("main", "net.backend");
	int select_backend = 0;

	dir_network = dir_network ? dir_network : ".";
	last_backend = last_backend ? last_backend : "";
	
	/* nacteni seznamu sitovych backendu */
	if (!(dir = g_dir_open(dir_network, 0, NULL))) {
		show_error_message(_("Nepovedlo se načíst seznam backendů"), _("Nelze otevřít \"%s\":\n%s"), dir_network, g_strerror(errno));
		perror("g_dir_open");
		return;
	}
	
	/* vytvoreni dialogu */
	dialog_connect = create_dialog_connect ();
	dir_combo = GTK_COMBO_BOX(lookup_widget(dialog_connect, "backend_combobox"));
	
	while((dir_name = (gchar*) g_dir_read_name(dir))) {
		if (dir_name[0] != '.') {
			DBG_MSG(8, "show_dialog_connect: found dir \"%s\"", dir_name);
			gtk_combo_box_prepend_text(dir_combo, dir_name);
			if (strcmp(dir_name, last_backend) == 0)
				select_backend = 0;
			else
				select_backend++;
		}
	}
	gtk_combo_box_set_active(dir_combo, select_backend);
	
	g_dir_close(dir);
	
	gtk_entry_set_text(GTK_ENTRY(lookup_widget(dialog_connect, "address_entry")), option_get_string("main", "net.address"));
	
	/* zobrazeni dialogu */
	gtk_window_set_transient_for(GTK_WINDOW(dialog_connect), GTK_WINDOW(main_window));
	gtk_widget_show (dialog_connect);
}

void show_dialog_game_select(void) {
	GDir *dir;
	gchar *dir_name;
	GtkTreeStore *store;
	GtkTreeIter iter;
	GtkCellRenderer *renderer;
	GtkTreeViewColumn *column;
	GtkTreeView *treeview;
	GtkTreeSelection *selection;
	const char *dir_game = option_get_string("main", "dir.game");
	const char *default_game = option_get_string("main", "game.backend");

	/* nacteni seznamu dostupnych her */
	if (!(dir = g_dir_open(dir_game, 0, NULL))) {
		show_error_message(_("Nepovedlo se načíst seznam her"), _("Nelze otevřít \"%s\":\n%s"), dir_game, g_strerror(errno));
		perror("g_dir_open");
		return;
	}
	
	/* vytvoreni dialogu */
	dialog_game_select = create_dialog_game_select();
	treeview = GTK_TREE_VIEW(lookup_widget(dialog_game_select, "game_select_treeview"));
	
	/* priprava modelu*/
	store = gtk_tree_store_new (1, G_TYPE_STRING);

	/* priprava widgetu */
	gtk_tree_view_set_model(treeview, GTK_TREE_MODEL(store));
	selection = gtk_tree_view_get_selection(treeview);
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);	
	renderer = gtk_cell_renderer_text_new();
	column = gtk_tree_view_column_new_with_attributes(_("Hra"), renderer, "text", 0, NULL);
	gtk_tree_view_append_column(treeview, column);
	gtk_tree_view_column_set_sort_column_id(column, 0);
	gtk_tree_view_set_search_column (treeview, 0);
	

	/* nasypani dat */
	while((dir_name = (gchar*) g_dir_read_name(dir))) {
		if (dir_name[0] != '.') {
			DBG_MSG(8, "show_dialog_game_select: found dir \"%s\"", dir_name);
			gtk_tree_store_append (store, &iter, NULL);
			gtk_tree_store_set(store, &iter, 0, dir_name, -1);
			if (default_game && strcmp(default_game, dir_name) == 0) {
				DBG_MSG(4, "show_dialog_game_select: selecting \"%s\"", dir_name);
				gtk_tree_selection_select_iter(selection, &iter);
			}
		}
	}
	g_dir_close(dir);
	g_object_unref(store);

	/* zobrazeni dialogu */
	gtk_window_set_transient_for(GTK_WINDOW(dialog_game_select), GTK_WINDOW(main_window));
	gtk_widget_show (dialog_game_select);
}

void show_error_message(char *title, char *fmt, ...) {
	GtkWidget *dialog;
	char *m;
	va_list ap;

	va_start(ap, fmt);
	if ((m = make_message(fmt, ap))) {
		dialog = gtk_message_dialog_new (GTK_WINDOW (main_window),
				GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
				GTK_MESSAGE_ERROR,
				GTK_BUTTONS_OK,
				title);
		gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), m);
		gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(main_window));
		gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
	}
	va_end(ap);
	free(m);
}

void switch_main_page(int page) {
	if (option_get_integer("main", "ui.autoswitch"))
		gtk_notebook_set_current_page(GTK_NOTEBOOK(lookup_widget(main_window, "main_notebook")), page);
}

void wait_for_callback(void) {
	gtk_main_iteration_do(TRUE);
}

void show_option_browser(void) {
	GtkCellRenderer *renderer;
	GtkTreeViewColumn *column;
	GtkTreeView *treeview;

	DBG_MSG(3, "show_option_browser");

	dialog_option_browser = create_dialog_option_browser();
	treeview = GTK_TREE_VIEW(lookup_widget(dialog_option_browser, "option_treeview"));

	option_set_update_callback(update_option_browser);
	
	/* column: option name */
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Kategorie"), renderer, "text", 0, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 0);

	/* column: option name */
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Volba"), renderer, "text", 1, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 1);

	/* column: option value */
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Hodnota"), renderer, "text", 2, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 2);
	
	/* column: option type */
	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Typ"), renderer, "text", 3, NULL);
	gtk_tree_view_column_set_resizable (column, TRUE);
	gtk_tree_view_append_column (treeview, column);
	gtk_tree_view_column_set_sort_column_id (column, 3);
	
	update_option_browser();
	
	/* show window */
	gtk_window_set_transient_for(GTK_WINDOW(dialog_option_browser), GTK_WINDOW(main_window));
	gtk_widget_show(dialog_option_browser);
}

void update_option_browser(void) {
	GtkListStore *store;
	GtkTreeIter iter;
	GtkTreeView *treeview = GTK_TREE_VIEW(lookup_widget(dialog_option_browser, "option_treeview"));
	char *name, *cat;
	const char *value;
	const char *type;
	int i;
	GtkAdjustment *vadj;

	if (!dialog_option_browser)
		return;

	DBG_MSG(2, "update_option_browser");

	/* save cursor position */
	vadj = gtk_tree_view_get_vadjustment(treeview);
	
	/* add data to the list store */
	store = gtk_list_store_new (4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
	gtk_tree_view_set_model(treeview, GTK_TREE_MODEL(store));
	for (i = 0; option_list_opt(NULL, &i, &cat, &name); i++) {
		if (name && name[0]) {
			value = option_get_string_by_id(i);
			type = option_get_type_name_by_id(i);
			DBG_MSG(6, "update_option_browser: adding option \"%s\"", name);
			gtk_list_store_append (store, &iter);
			gtk_list_store_set (store, &iter, 0, cat, 1, name, 2, value, 3, type, -1);
		}
	}
	g_object_unref(store);

	/* restore position */
	if (vadj)
		gtk_tree_view_set_vadjustment(treeview, vadj);

	gtk_tree_view_columns_autosize(treeview);

}


void update_playerlist(void) {
	GtkListStore *store;
	GtkTreeIter iter;
	GtkTreeView *treeview = GTK_TREE_VIEW(lookup_widget(main_window, "players_treeview"));
	char *nick, *address, *role, *score, *conn_state;
	int i = 0, ack;
	GtkAdjustment *vadj;
	gchar *ack_icon[] = {"gtk-stop", "gtk-cancel", NULL, "gtk-index", "gtk-apply"};

	DBG_MSG(2, "update_playerlist");

	/* save cursor position */
	vadj = gtk_tree_view_get_vadjustment(treeview);
	
	/* add data to the list store */
	store = gtk_list_store_new (6, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
	gtk_tree_view_set_model(treeview, GTK_TREE_MODEL(store));
	for (i = 0; playerlist_list(&i, &address, &nick, &role, &score, &conn_state, &ack); i++) {
		if (address) {
			DBG_MSG(6, "update_playerlist: adding player \"%s\"", address);
			gtk_list_store_append (store, &iter);
			gtk_list_store_set (store, &iter,
					0, ack_icon[ack + 2],
					1, nick ? nick : "",
					2, address ? address : "",
					3, role ? role : "",
					4, score ? score : "",
					5, conn_state ? conn_state : "",
					-1);
		}
	}
	g_object_unref(store);

	/* restore position */
	if (vadj)
		gtk_tree_view_set_vadjustment(treeview, vadj);

	gtk_tree_view_columns_autosize(treeview);

}

void store_options_with_info(void) {
	char *err = NULL;

	append_to_chat("-- Ukládám data...");
	if (option_store_to_default()) {
		append_to_chat(" Ok.\n\n");
	} else {
		err = g_locale_to_utf8(strerror(option_last_error), -1, NULL, NULL, NULL);
		append_to_chat(" Chyba: %s.", err);
		free(err);
	}
}


void gui_role_clear(void)
{
	static GtkComboBox *c = NULL;
	if (!c) c = GTK_COMBO_BOX(lookup_widget(main_window, "game_role_combobox"));
	gtk_list_store_clear (GTK_LIST_STORE (gtk_combo_box_get_model (c)));
	gtk_combo_box_append_text(c, "pozorovatel");
	gtk_combo_box_set_active(c, 0);
}


void gui_role_add(char *role)
{
	static GtkComboBox *c = NULL;
	assert(role != NULL);
	if (!c) c = GTK_COMBO_BOX(lookup_widget(main_window, "game_role_combobox"));
	gtk_combo_box_append_text(c, role);
}


int gui_exit_question(void)
{
	gint response = GTK_RESPONSE_ACCEPT;
	GtkWidget *d;
	
	if (get_status() != S_OFFLINE) {
		d = gtk_message_dialog_new(GTK_WINDOW(main_window), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION,
				GTK_BUTTONS_NONE, _("Opravdu ukončit?"));
		gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d),
				_("Ukončení programu způsobí uzavření spojení s ostatními hráči"
					" a případně i předčasné ukončení rozehraných her."));
		gtk_dialog_add_buttons(GTK_DIALOG(d),
				GTK_STOCK_QUIT, GTK_RESPONSE_ACCEPT,
				GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
				NULL);
		gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_REJECT);
		response = gtk_dialog_run(GTK_DIALOG(d));
		gtk_widget_destroy(d);
	}

	return response == GTK_RESPONSE_ACCEPT;
}
