/*
 * This file is part of roccat-tools.
 *
 * roccat-tools 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.
 *
 * roccat-tools 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 roccat-tools. If not, see <http://www.gnu.org/licenses/>.
 */

#include "ryosconfig_application.h"
#include "roccat_config_window.h"
#include "ryosconfig_configuration_dialog.h"
#include "ryosconfig_profile_page.h"
#include "ryosconfig_settings_page.h"
#include "ryosconfig_update_assistant.h"
#include "roccat_warning_dialog.h"
#include "roccat_save_dialog.h"
#include "roccat_text_dialog.h"
#include "dbus_roccat_helper.h"

struct _RyosconfigApplication {
	RoccatDevice *ryos;
	RoccatDeviceScanner *device_scanner;
	RoccatConfigWindow *window;
	RyosconfigProfilePage *profile_pages[RYOS_PROFILE_NUM];
	RyosconfigSettingsPage *settings_page;
	RoccatKeyFile *config;
	DBusGProxy *dbus_proxy;
	guint actual_profile_index;
};

static gboolean warn_if_no_device(RyosconfigApplication *app) {
	return roccat_no_device_warning_dialog(GTK_WINDOW(app->window), app->ryos, RYOS_DEVICE_NAME);
}

static void settings_page_actual_profile_changed_cb(RyosconfigSettingsPage *settings_page, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	guint profile_index = ryosconfig_settings_page_get_actual_profile(app->settings_page);
	GError *local_error = NULL;

	if (!warn_if_no_device(app))
		return;

	if (app->actual_profile_index != profile_index) {
		app->actual_profile_index = profile_index;
		ryos_profile_write(app->ryos, profile_index, &local_error);
		if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error activating profile", &local_error))
			return;
		ryos_dbus_emit_profile_changed_outside(app->dbus_proxy, profile_index);
	}
}

static void device_reset_cb(RyosconfigSettingsPage *settings_page, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	RyosRkp *rkp;
	guint i;
	GError *error = NULL;

	if (!warn_if_no_device(app))
		return;

	ryos_reset(app->ryos, RYOS_RESET_FUNCTION_RESET, &error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error resetting device", &error))
		return;

	for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
		rkp = ryos_rkp_load_save_after_reset(app->ryos, i, &error);
		ryosconfig_profile_page_set_rkp(app->profile_pages[i], rkp);
		ryos_rkp_free(rkp);
		ryos_dbus_emit_profile_data_changed_outside(app->dbus_proxy, i);
	}
}

static void actual_profile_changed_from_device_cb(DBusGProxy *proxy, guchar profile_index, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;

	if (app->actual_profile_index != profile_index) {
		app->actual_profile_index = profile_index;
		ryosconfig_settings_page_set_actual_profile(app->settings_page, profile_index);
	}
}

static void brightness_changed_from_device_cb(DBusGProxy *proxy, guchar profile_index, guchar brightness_index, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	ryosconfig_profile_page_update_brightness(app->profile_pages[profile_index], brightness_index);
}

static void macro_changed_from_device_cb(DBusGProxy *proxy, guchar profile_index, guchar button_index, gchar const *data, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	RyosMacro *macro;
	gsize length;

	macro = (RyosMacro *)g_base64_decode(data, &length);
	if (length == sizeof(RyosMacro))
		ryosconfig_profile_page_update_key(app->profile_pages[profile_index], button_index, macro);
	g_free(macro);
}

static gboolean settings_page_set_info(RyosconfigApplication *app) {
	GError *local_error = NULL;
	RyosInfo *info;

	info = ryos_info_read(app->ryos, &local_error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Can't read info:", &local_error))
		return FALSE;
	ryosconfig_settings_page_set_info(app->settings_page, info);
	g_free(info);
	return TRUE;
}

static gboolean add_cb(RoccatDevice *device, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	GError *local_error = NULL;
	guint i;
	RyosRkp *rkp;
	gchar *device_name;

	if (app->ryos) {
		roccat_multiple_device_warning_dialog(GTK_WINDOW(app->window), RYOS_DEVICE_NAME);
		return TRUE;
	}

	app->ryos = device;

	app->actual_profile_index = ryos_profile_read(app->ryos, &local_error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Can't read actual profile:", &local_error))
		goto error;
	ryosconfig_settings_page_set_actual_profile(app->settings_page, app->actual_profile_index);

	if (!settings_page_set_info(app))
		goto error;

	for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
		ryosconfig_profile_page_set_device(app->profile_pages[i], app->ryos);

		rkp = ryosconfig_profile_page_get_rkp(app->profile_pages[i]);
		ryos_rkp_update_from_device(app->ryos, rkp, i, &local_error);

		if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Can't read hardware profile data:", &local_error)) {
			ryos_rkp_free(rkp);
			break;
		}

		ryosconfig_profile_page_set_rkp(app->profile_pages[i], rkp);

		ryos_rkp_free(rkp);
	}

	dbus_g_proxy_connect_signal(app->dbus_proxy, "ProfileChanged", G_CALLBACK(actual_profile_changed_from_device_cb), app, NULL);
	dbus_g_proxy_connect_signal(app->dbus_proxy, "BrightnessChanged", G_CALLBACK(brightness_changed_from_device_cb), app, NULL);
	dbus_g_proxy_connect_signal(app->dbus_proxy, "MacroChanged", G_CALLBACK(macro_changed_from_device_cb), app, NULL);

	device_name = ryos_device_name(device);
	roccat_config_window_set_title_connected(app->window, device_name);
	g_free(device_name);

	return FALSE;
error:
	app->ryos = NULL;
	return TRUE;
}

static gboolean remove_cb(RoccatDevice *device, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;

	dbus_g_proxy_disconnect_signal(app->dbus_proxy, "ProfileChanged", G_CALLBACK(actual_profile_changed_from_device_cb), app);
	dbus_g_proxy_disconnect_signal(app->dbus_proxy, "BrightnessChanged", G_CALLBACK(brightness_changed_from_device_cb), app);
	dbus_g_proxy_disconnect_signal(app->dbus_proxy, "MacroChanged", G_CALLBACK(macro_changed_from_device_cb), app);

	roccat_device_free(app->ryos);
	app->ryos = NULL;

	ryosconfig_settings_page_clear_info(app->settings_page);
	roccat_config_window_set_title_disconnected(app->window);

	return TRUE;
}

static gboolean save_unsaved(RyosconfigApplication *app, RyosRkp *rkp, guint profile_index, GError **error) {
	if (app->ryos)
		ryos_rkp_save(app->ryos, rkp, profile_index, error);
	else
		ryos_rkp_save_actual(rkp, profile_index, error);

	if (*error)
		return FALSE;
	else {
		ryos_dbus_emit_profile_data_changed_outside(app->dbus_proxy, profile_index);
		ryosconfig_profile_page_set_rkp(app->profile_pages[profile_index], rkp);
		return TRUE;
	}
}

static gboolean display_quit_dialog(RyosconfigApplication *app) {
	guint i;
	gboolean modified;
	RyosRkp *rkps[RYOS_PROFILE_NUM];
	gboolean retval;
	GError *error = NULL;

	modified = FALSE;
	for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
		rkps[i] = ryosconfig_profile_page_get_rkp(app->profile_pages[i]);
		if (ryos_rkp_get_modified(rkps[i]))
			modified = TRUE;
	}
	if (!modified) {
		for (i = 0; i < RYOS_PROFILE_NUM; ++i)
			ryos_rkp_free(rkps[i]);
		return TRUE;
	}

	switch (roccat_save_unsaved_dialog(GTK_WINDOW(app->window), TRUE)) {
	case GTK_RESPONSE_CANCEL:
		retval = FALSE;
		break;
	case GTK_RESPONSE_ACCEPT:
		retval = TRUE;
		warn_if_no_device(app);
		for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
			if (!save_unsaved(app, rkps[i], i, &error)) {
				retval = FALSE;
				break;
			}
		}
		roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error storing unsaved data", &error);
		break;
	default:
		retval = TRUE;
		break;
	}

	for (i = 0; i < RYOS_PROFILE_NUM; ++i)
		ryos_rkp_free(rkps[i]);

	return retval;
}

static gboolean delete_event_cb(GtkWidget *window, GdkEvent *event, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;

	return !display_quit_dialog(app);
}

static void destroy_event_cb(GtkWidget *window, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	gtk_main_quit();
	app->window = NULL;
}

static void save_profile_to_device_cb(RyosconfigProfilePage *profile_page, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	RyosRkp *rkp = ryosconfig_profile_page_get_rkp(profile_page);
	guint profile_index = ryosconfig_profile_page_get_index(profile_page);
	GError *error = NULL;

	warn_if_no_device(app);
	save_unsaved(app, rkp, profile_index, &error);
	roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error storing unsaved data", &error);

	ryos_rkp_free(rkp);
}

static void add_file_filter_to_file_chooser(GtkFileChooser *chooser) {
	GtkFileFilter *filter;
	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "Ryos Windows profiles");
	gtk_file_filter_add_pattern(filter, "*.rkp");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(chooser), filter);

	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "All files");
	gtk_file_filter_add_pattern(filter, "*");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(chooser), filter);
}

static void save_profile_to_file_cb(RyosconfigProfilePage *profile_page, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	guint profile_index = ryosconfig_profile_page_get_index(profile_page);
	RyosRkp *rkp;

	dialog = gtk_file_chooser_dialog_new("Save profile",
			GTK_WINDOW(app->window),
			GTK_FILE_CHOOSER_ACTION_SAVE,
			GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
			GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
			NULL);

	add_file_filter_to_file_chooser(GTK_FILE_CHOOSER(dialog));
	path = ryos_configuration_get_rkp_path(app->config);
	gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), path);
	g_free(path);

	if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
		filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
		path = g_path_get_dirname(filename);
		ryos_configuration_set_rkp_path(app->config, path);
		g_free(path);

		rkp = ryosconfig_profile_page_get_rkp(app->profile_pages[profile_index]);
		ryos_rkp_write_with_path(filename, rkp, &error);
		ryos_rkp_free(rkp);
		if (error) {
			roccat_warning_dialog(GTK_WINDOW(dialog), "Error saving rkp", error->message);
			g_error_free(error);
		}

		g_free(filename);
	}
	gtk_widget_destroy(dialog);
}

static void load_profile_from_file_cb(RyosconfigProfilePage *profile_page, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	RyosRkp *rkp;
	guint profile_index = ryosconfig_profile_page_get_index(profile_page);

	dialog = gtk_file_chooser_dialog_new("Load profile",
			GTK_WINDOW(app->window),
			GTK_FILE_CHOOSER_ACTION_OPEN,
			GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
			GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
			NULL);

	add_file_filter_to_file_chooser(GTK_FILE_CHOOSER(dialog));
	path = ryos_configuration_get_rkp_path(app->config);
	gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), path);
	g_free(path);

	if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
		filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
		path = g_path_get_dirname(filename);
		ryos_configuration_set_rkp_path(app->config, path);
		g_free(path);

		rkp = ryos_rkp_read_with_path(filename); // FIXME better without default but with error
		if (error) {
			roccat_warning_dialog(GTK_WINDOW(dialog), "Error loading rkp", error->message);
			g_error_free(error);
		} else {
			ryos_rkp_set_modified(rkp);
			ryosconfig_profile_page_set_rkp(app->profile_pages[profile_index], rkp);
			ryos_rkp_free(rkp);
		}

		g_free(filename);
	}

	gtk_widget_destroy(dialog);
}

static void save_all_cb(GtkMenuItem *item, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	RyosRkp *rkp;
	guint i;
	GError *error = NULL;

	warn_if_no_device(app);
	for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
		rkp = ryosconfig_profile_page_get_rkp(app->profile_pages[i]);
		save_unsaved(app, rkp, i, &error);
		roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error storing unsaved data", &error);

		ryos_rkp_free(rkp);
	}
}

static void edit_preferences_cb(GtkMenuItem *item, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	ryosconfig_configuration_dialog(GTK_WINDOW(app->window), app->config);
	ryos_dbus_emit_configuration_changed_outside(app->dbus_proxy);
}

static void menu_misc_firmware_update_cb(GtkMenuItem *item, gpointer user_data) {
	RyosconfigApplication *app = (RyosconfigApplication *)user_data;
	if (warn_if_no_device(app))
		ryosconfig_update_assistant(GTK_WINDOW(app->window), &app->ryos);
}

static GtkWidget *menu_misc_new(RyosconfigApplication *app) {
	GtkWidget *menu_item;
	GtkWidget *sub_menu;
	GtkWidget *submenu_item;

	menu_item = gtk_menu_item_new_with_label("Misc");
	sub_menu = gtk_menu_new();
	gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), sub_menu);

	submenu_item = gtk_image_menu_item_new_with_label("Firmware update");
	gtk_menu_shell_append(GTK_MENU_SHELL(sub_menu), submenu_item);
	g_signal_connect(G_OBJECT(submenu_item), "activate", G_CALLBACK(menu_misc_firmware_update_cb), app);

	gtk_widget_show_all(menu_item);

	return menu_item;
}

RyosconfigApplication *ryosconfig_application_new(void) {
	RyosconfigApplication *app;
	RyosRkp *rkp;
	GtkWidget *tab_label;
	guint i;
	GtkMenuItem *preferences_menu;

	app = (RyosconfigApplication *)g_malloc0(sizeof(RyosconfigApplication));

	app->config = ryos_configuration_load();

	app->window = ROCCAT_CONFIG_WINDOW(roccat_config_window_new(RYOS_DEVICE_NAME_COMBINED));
	gtk_window_resize(GTK_WINDOW(app->window), 640, 480);
	gtk_widget_show(GTK_WIDGET(app->window));

	for (i = 0; i < RYOS_PROFILE_NUM; ++i) {
		app->profile_pages[i] = RYOSCONFIG_PROFILE_PAGE(ryosconfig_profile_page_new(i));
		tab_label = ryosconfig_profile_page_get_tab_label(app->profile_pages[i]);
		roccat_config_window_append_page(app->window, GTK_WIDGET(app->profile_pages[i]), tab_label);

		rkp = ryos_rkp_load_actual(i);
		ryosconfig_profile_page_set_rkp(app->profile_pages[i], rkp);
		ryos_rkp_free(rkp);

		g_signal_connect(G_OBJECT(app->profile_pages[i]), "load-from-file", G_CALLBACK(load_profile_from_file_cb), app);
		g_signal_connect(G_OBJECT(app->profile_pages[i]), "save-to-file", G_CALLBACK(save_profile_to_file_cb), app);
		g_signal_connect(G_OBJECT(app->profile_pages[i]), "save-to-device", G_CALLBACK(save_profile_to_device_cb), app);
	}

	app->settings_page = RYOSCONFIG_SETTINGS_PAGE(ryosconfig_settings_page_new());
	roccat_config_window_append_page(app->window, GTK_WIDGET(app->settings_page), gtk_label_new("Settings"));

	preferences_menu = GTK_MENU_ITEM(gtk_image_menu_item_new_from_stock(GTK_STOCK_PREFERENCES, NULL));
	g_signal_connect(G_OBJECT(preferences_menu), "activate", G_CALLBACK(edit_preferences_cb), app);
	roccat_config_window_edit_menu_append(app->window, preferences_menu);

	roccat_config_window_menu_insert(app->window, GTK_MENU_ITEM(menu_misc_new(app)));

	g_signal_connect(G_OBJECT(app->settings_page), "actual-profile-changed", G_CALLBACK(settings_page_actual_profile_changed_cb), app);
	g_signal_connect(G_OBJECT(app->settings_page), "device-reset", G_CALLBACK(device_reset_cb), app);
	g_signal_connect(G_OBJECT(app->window), "destroy", G_CALLBACK(destroy_event_cb), app);
	g_signal_connect(G_OBJECT(app->window), "delete-event", G_CALLBACK(delete_event_cb), app);
	g_signal_connect(G_OBJECT(app->window), "save-all", G_CALLBACK(save_all_cb), app);

	/* keep this order */
	app->dbus_proxy = ryos_dbus_proxy_new();
	app->device_scanner = ryos_device_scanner_new(add_cb, remove_cb, app);

	/* if a device is already plugged in, add_cb has already been executed */
	warn_if_no_device(app);

	return app;
}

void ryosconfig_application_free(RyosconfigApplication *app) {
	roccat_device_scanner_free(app->device_scanner);
	app->device_scanner = NULL;

	dbus_roccat_proxy_free(app->dbus_proxy);
	app->dbus_proxy = NULL;

	roccat_device_free(app->ryos);
	app->ryos = NULL;

	if (app->window) {
		gtk_widget_destroy(GTK_WIDGET(app->window));
		app->window = NULL;
	}

	ryosconfig_configuration_save(GTK_WINDOW(app->window), app->config);
	ryos_configuration_free(app->config);
	app->config = NULL;

	g_free(app);
}
