/* vim:set encoding=utf8: */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

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

#define DEBUG 		0
#include "debug.h"

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


GtkWidget *dialog_connect = NULL;
GtkWidget *dialog_about = NULL;
GtkWidget *dialog_game_select = NULL;
GtkWidget *dialog_option_browser = NULL;


/*****************************************************************************
 * 	GUI Callbacks
 ****************************************************************************/

gboolean
on_main_window_destroy                 (GtkWidget       *widget,
                                        GdkEvent        *event,
                                        gpointer         user_data)
{
	
	if (gui_exit_question())
		switch_to_status(S_EXITING);

	return TRUE;
}


void
on_chat_entry_activate                 (GtkEntry        *entry,
                                        gpointer         user_data)
{
	char *msg = (char*)gtk_entry_get_text(entry);
	MESSAGE *m;
	
	if (msg[0] == '/' && msg[1] != '/') {
		/* game backend */
		m = message_create('C', 'G');
		message_append(m, MESSAGE_STRING, "G/", MESSAGE_STRING, msg + 1, MESSAGE_END);
	} else {
		/* klasicky chat */
		m = message_create('C', 'N');
		message_append(m, MESSAGE_STRING, "C", MESSAGE_STRING, msg, MESSAGE_END);
	}
	message_send(m);
	message_destroy(m);

	/* vymazat text z chat_entry */
	gtk_entry_set_text(GTK_ENTRY(lookup_widget(main_window, "chat_entry")), "");
}

/****************************************************************************/

void
on_connect_btn_cancel_clicked          (GtkButton       *button,
                                        gpointer         user_data)
{
	gtk_widget_destroy(dialog_connect);
}


void
on_connect_btn_ok_clicked              (GtkButton       *button,
                                        gpointer         user_data)
{
	char *str;
		
	GtkTreeIter backend_iter;

	gtk_widget_hide(dialog_connect);


	option_set_string("main", "net.address", gtk_entry_get_text(GTK_ENTRY(lookup_widget(dialog_connect, "address_entry"))));

	if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(lookup_widget(dialog_connect, "backend_combobox")), &backend_iter)) {
		gtk_tree_model_get(gtk_combo_box_get_model(GTK_COMBO_BOX(lookup_widget(dialog_connect, "backend_combobox"))),
				&backend_iter, 0, &str, -1);
		option_set_string("main", "net.backend", str ? str : "");
		switch_to_status(S_CONNECTING);
	} else {
		option_set_string("main", "net.backend", "");
	}


	gtk_widget_destroy(dialog_connect);
	update_main_window();
}


/****************************************************************************/

void
on_dialog_connect_destroy              (GtkObject       *object,
                                        gpointer         user_data)
{

}

/****************************************************************************/

void
on_btn_about_close_clicked             (GtkButton       *button,
                                        gpointer         user_data)
{
	gtk_widget_destroy(dialog_about);
}

void
on_dialog_about_destroy                (GtkObject       *object,
                                        gpointer         user_data)
{
	gtk_widget_destroy(dialog_about);
}



void
on_btn_restart_clicked                 (GtkToolButton   *toolbutton,
                                        gpointer         user_data)
{
}


void
on_main_notebook_switch_page           (GtkNotebook     *notebook,
                                        GtkNotebookPage *page,
                                        guint            page_num,
                                        gpointer         user_data)
{
	switch (page_num) {
		case GUI_PAGE_DESK:
			gtk_widget_hide(lookup_widget(main_window, "desk_label_image"));
			break;
		case GUI_PAGE_CHAT:
			gtk_widget_hide(lookup_widget(main_window, "chat_label_image"));
			break;
	}

}


gboolean
on_desk_drawingarea_expose             (GtkWidget       *widget,
                                        GdkEventExpose  *event,
                                        gpointer         user_data)
{
	if (draw_board) {
		gdk_draw_pixbuf(widget->window, NULL, draw_board,
				event->area.x, event->area.y,
				event->area.x, event->area.y,
				event->area.width, event->area.height,
				GDK_RGB_DITHER_NORMAL, 0, 0);
	}

	return TRUE;
}


gboolean
on_desk_drawingarea_button_press_event (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	MESSAGE *m;
	int object;

	object = draw_get_object_by_xy(event->x, event->y);
	m = message_create('B', 'G');
	message_append(m, MESSAGE_STRING, "Bbp",
			MESSAGE_INTEGER, (int)event->button,
			MESSAGE_INTEGER, (int)object,
			MESSAGE_INTEGER, (int)event->x,
			MESSAGE_INTEGER, (int)event->y,
			MESSAGE_END);
	message_send(m);
	message_destroy(m);
	DBG_MSG(3, "Button press event: button %d at [ %0.0lf, %0.0lf ]", event->button, event->x, event->y);
	return FALSE;
}


gboolean
on_desk_drawingarea_button_release_event
                                        (GtkWidget      *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
	MESSAGE *m;
	int object;

	object = draw_get_object_by_xy(event->x, event->y);
	m = message_create('B', 'G');
	message_append(m, MESSAGE_STRING, "Bbr",
			MESSAGE_INTEGER, (int)event->button,
			MESSAGE_INTEGER, (int)object,
			MESSAGE_INTEGER, (int)event->x,
			MESSAGE_INTEGER, (int)event->y,
			MESSAGE_END);
	message_send(m);
	message_destroy(m);
	DBG_MSG(3, "Button release event: button %d at [ %0.0lf, %0.0lf ]", event->button, event->x, event->y);
	return FALSE;
}


gboolean
on_desk_drawingarea_key_press_event    (GtkWidget       *widget,
                                        GdkEventKey     *event,
                                        gpointer         user_data)
{
	MESSAGE *m;
	m = message_create('B', 'G');
	message_append(m, MESSAGE_STRING, "Bkp",
			MESSAGE_INTEGER, event->state,
			MESSAGE_INTEGER, event->keyval,
			MESSAGE_STRING, event->string,
			MESSAGE_END);
	message_send(m);
	message_destroy(m);
	DBG_MSG(3, "Key press event: keyval %d, string \"%s\", mods 0x%04x", event->keyval, event->string, event->state);
	return TRUE;
}


gboolean
on_desk_drawingarea_key_release_event  (GtkWidget       *widget,
                                        GdkEventKey     *event,
                                        gpointer         user_data)
{
	MESSAGE *m;
	m = message_create('B', 'G');
	message_append(m, MESSAGE_STRING, "Bkr",
			MESSAGE_INTEGER, event->state,
			MESSAGE_INTEGER, event->keyval,
			MESSAGE_STRING, event->string,
			MESSAGE_END);
	message_send(m);
	message_destroy(m);
	DBG_MSG(3, "Key release event: keyval %d, string \"%s\", mods 0x%04x", event->keyval, event->string, event->state);
	return TRUE;
}

/*****************************************************************************
 *	Menu
 ****************************************************************************/

/***** Connect *****/

void
on_network_connect_activate            (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	show_dialog_connect();
}


void
on_network_disconnect_activate         (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	switch_to_status(S_DISCONNECTING);
}


void
on_mnu_exit_activate                   (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	if (gui_exit_question())
		switch_to_status(S_EXITING);
}

/***** Game *****/

void
on_game_select_activate                (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	show_dialog_game_select();
}


void
on_game_start_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	switch_to_status(S_GAME_CHECK);
}


void
on_game_surrender_activate             (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_game_terminate_activate             (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	if (backend_game) {
		append_to_chat("-- Ukončuji herní backend ...\n");
		backend_kill(backend_game);
	}
}


void
on_game_synchronize_activate           (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_game_pause_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	gui.is_paused = gtk_check_menu_item_get_active(
			GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "game_pause")));
	set_statusbar_text(gui.is_paused ? _("Hra pozastavena") : "");
	update_main_window();
}


void
on_game_load_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_game_save_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_game_lock_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	gui.is_locked = gtk_check_menu_item_get_active(
			GTK_CHECK_MENU_ITEM(lookup_widget(main_window, "game_lock")));
	update_main_window();
}

/***** Preferences *****/

void
on_pref_animate_activate               (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_players_columns_activate            (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	char *opt = (char *) user_data;
	option_set_integer("main", opt, gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem)));
	update_main_window();
}


void
on_pref_autoswitch_activate            (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	option_set_integer("main", "ui.autoswitch", gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem)));
}


void
on_pref_highlightlast_activate         (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}

void
on_pref_showlogs_activate              (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))) {
		gtk_widget_show(lookup_widget(main_window, "gamelog_scrolledwindow"));
		gtk_widget_show(lookup_widget(main_window, "netlog_scrolledwindow"));
		option_set_integer("main", "ui.show_logs", 1);
	} else {
		gtk_widget_hide(lookup_widget(main_window, "gamelog_scrolledwindow"));
		gtk_widget_hide(lookup_widget(main_window, "netlog_scrolledwindow"));
		option_set_integer("main", "ui.show_logs", 0);
	}
}


void
on_pref_cleanlogs_activate             (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	erase_logs();
}


void
on_pref_config_activate                (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}


void
on_pref_browser_activate               (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	if (dialog_option_browser)
		gtk_widget_grab_focus(dialog_option_browser);
	else
		show_option_browser();
}


void
on_pref_save_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	store_options_with_info();
}

/***** Test *****/

void
on_test_draw_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	const char *dir_test = option_get_string("main", "dir.data");
	set_statusbar_text(_("Test: Vykreslovací test"));
	draw_remove_all();
	draw_image_load(dir_test, "test/sachovnice.png", 0);
	draw_object_add(0, 0, 0, 0, -1, -1);
	draw_image_load(dir_test, "test/kurzor.png", 1);
	draw_object_add(1, 1, 128, 128, -1, -1);
	draw_object_add(2, 1, 64, 384, -1, -1);
	draw_image_load(dir_test, "test/kurzor2.png", 2);
	draw_object_add(3, 2, 320, 256, -1, -1);
	draw_object_add(4, 2, 384, 384, -1, -1);
	draw_image_load(dir_test, "test/figurka.png", 10);
	draw_object_add(10, 10, 128, 128, -1, -1);
	draw_object_add(11, 10, 128, 256, -1, -1);
	draw_object_add(12, 10, 320, 128, -1, -1);
	draw_object_add(13, 10, 320, 256, -1, -1);
	switch_main_page(GUI_PAGE_DESK);
	draw_all();
}


void
on_test_clean_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	set_statusbar_text(_("Test: Vymazání hrací desky"));
	draw_remove_all();
	switch_main_page(GUI_PAGE_DESK);
	draw_all();
}


void
on_test_memusage_activate              (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	long mem_size, mem_resident, mem_shared;
	const char *filename = "/proc/self/statm";
	FILE *f;
	
	DBG_MSG(1, "on_test_memusage_activate");
	f = fopen(filename, "rt");
	if (f) {
		fscanf(f, " %ld %ld %ld", &mem_size, &mem_resident, &mem_shared);
		append_to_chat(_("-- Memory usage: %ld B total, %ld B resident, %ld B shared\n"), mem_size, mem_resident, mem_shared);
		fclose(f);
	} else {
		append_to_chat("-- %s: %s\n", filename, g_strerror(errno));
	}
}

/***** Help *****/

void
on_help_about_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *dialog;
	
	dialog = gtk_about_dialog_new();
	gtk_about_dialog_set_name(GTK_ABOUT_DIALOG(dialog), "Net Board");
	gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(dialog), "2");
	gtk_about_dialog_set_copyright(GTK_ABOUT_DIALOG(dialog), "Josef Kufner <jk@myserver.cz>");
	gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG(dialog),
			_("Univerzální dvourozměrná hrací deska.\n"
			"Vytvořeno jako semestrální práce\n"
			"na ČVUT - FEL v roce 2005\n"
			"a překopáno jako semestrální\n"
			"projekt v roce 2007.\n"));
	gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(dialog), "http://jk.myserver.cz/programy/netboard/");
	gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(main_window));
	gtk_dialog_run(GTK_DIALOG(dialog));
}


void
on_hlp_rules_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{

}

/*****************************************************************************/

void
on_game_role_combobox_changed          (GtkComboBox     *combobox,
                                        gpointer         user_data)
{
	gchar *role, *desc;
	MESSAGE *msg;

	role = gtk_combo_box_get_active_text(combobox);
	if (role) {
		option_set_string("main", "game.my_role", role);
		desc = g_strdup_printf("Budu hrát jako \"%s\"", role);
		msg = message_create('S', 'N');
		message_append(msg, MESSAGE_STRING, "Spr",
				MESSAGE_STRING, desc,
				MESSAGE_STRING, role,
				MESSAGE_END);
		message_send(msg);
		message_destroy(msg);

		g_free(desc);
		g_free(role);
	}

	gtk_widget_set_sensitive((GtkWidget *)combobox, FALSE);
	gtk_widget_set_sensitive(lookup_widget(main_window, "game_start_button"), FALSE);
}


void
on_game_name_button_clicked            (GtkButton       *button,
                                        gpointer         user_data)
{
	show_dialog_game_select();
}


void
on_game_start_button_clicked           (GtkButton       *button,
                                        gpointer         user_data)
{
	on_game_start_activate(NULL, user_data);
}


void
on_dialog_game_select_destroy          (GtkObject       *object,
                                        gpointer         user_data)
{

}


void
on_game_select_cancelbutton_clicked    (GtkButton       *button,
                                        gpointer         user_data)
{
	gtk_widget_destroy(dialog_game_select);
}


void
on_game_select_okbutton_clicked        (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkTreeView *treeview = GTK_TREE_VIEW(lookup_widget(dialog_game_select, "game_select_treeview"));
	GtkTreeIter iter;
	GtkTreeModel *model;
	GtkTreeSelection *selection = gtk_tree_view_get_selection(treeview);
	gchar *str = NULL;
	
	/* nacist vybranou hry a nastavit ji do labelu */
	if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
		gtk_tree_model_get(model, &iter, 0, &str, -1);
	}

	DBG_MSG(2, "on_game_select_okbutton_clicked: game backend = \"%s\"", str);
	option_set_string("main", "game.backend", str);

	if (str) {
		switch_to_status(S_LOAD_STARTING);
	}

	gtk_widget_destroy(dialog_game_select);
}


void
on_dialog_option_browser_destroy       (GtkObject       *object,
                                        gpointer         user_data)
{
	option_set_update_callback(NULL);
	dialog_option_browser = NULL;
}



void
on_connection_connect_button_activate  (GtkButton       *button,
                                        gpointer         user_data)
{
	show_dialog_connect();
}

/* vim:set encoding=utf8: */
