/*
 * 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 "arvoconfig_application.h"
#include "roccat_config_window.h"
#include "arvoconfig_configuration_dialog.h"
#include "arvoconfig_profile_page.h"
#include "arvoconfig_settings_page.h"
#include "roccat_warning_dialog.h"
#include "roccat_save_dialog.h"
#include "roccat_text_dialog.h"
#include "dbus_roccat_helper.h"

struct _ArvoconfigApplication {
	RoccatDevice *arvo;
	RoccatDeviceScanner *device_scanner;
	RoccatConfigWindow *window;
	ArvoconfigProfilePage *profile_pages[ARVO_PROFILE_NUM];
	ArvoconfigSettingsPage *settings_page;
	RoccatKeyFile *config;
	DBusGProxy *dbus_proxy;
	guint actual_profile_index;
	ArvoRkp *rkps[ARVO_PROFILE_NUM];
};

static gboolean warn_if_no_device(ArvoconfigApplication *app) {
	return roccat_no_device_warning_dialog(GTK_WINDOW(app->window), app->arvo, ARVO_DEVICE_NAME);
}

static void settings_page_actual_profile_changed_cb(ArvoconfigSettingsPage *settings_page, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	guint profile_number = arvoconfig_settings_page_get_actual_profile(app->settings_page);
	guint profile_index = profile_number - 1;
	GError *local_error = NULL;

	if (!warn_if_no_device(app))
		return;

	if (app->actual_profile_index != profile_index) {
		app->actual_profile_index = profile_index;
		arvo_profile_activate(app->arvo, profile_number, app->rkps[profile_index], &local_error);
		if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error activating profile", &local_error))
			return;
		arvo_dbus_emit_profile_changed_outside(app->dbus_proxy, profile_number);
	}
}

static void actual_profile_changed_from_device_cb(DBusGProxy *proxy, guchar profile_number, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	guint profile_index = profile_number - 1;

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

static gboolean settings_page_set_info(ArvoconfigApplication *app) {
	GError *local_error = NULL;
	ArvoInfo *info;

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

static gboolean add_cb(RoccatDevice *device, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	GError *error = NULL;
	guint profile_number;

	if (app->arvo) {
		roccat_multiple_device_warning_dialog(GTK_WINDOW(app->window), ARVO_DEVICE_NAME);
		return TRUE;
	}

	app->arvo = device;

	profile_number = arvo_actual_profile_read(app->arvo, &error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Can't read actual profile:", &error))
		goto error;
	app->actual_profile_index = profile_number - 1;
	arvoconfig_settings_page_set_actual_profile(app->settings_page, profile_number);

	if (!settings_page_set_info(app))
		goto error;

	dbus_g_proxy_connect_signal(app->dbus_proxy, "ProfileChanged", G_CALLBACK(actual_profile_changed_from_device_cb), app, NULL);

	roccat_config_window_set_title_connected(app->window, ARVO_DEVICE_NAME);

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

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

	dbus_g_proxy_disconnect_signal(app->dbus_proxy, "ProfileChanged", G_CALLBACK(actual_profile_changed_from_device_cb), app);

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

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

	return TRUE;
}

static gboolean save_unsaved(ArvoconfigApplication *app, ArvoRkp *rkp, guint profile_index, GError **error) {
	guint profile_number = profile_index + 1;

	if (app->arvo)
		arvo_rkp_save(app->arvo, rkp, profile_number, error);
	else
		arvo_rkp_save_actual(rkp, profile_number, error);

	if (*error)
		return FALSE;
	else {
		arvo_rkp_free(app->rkps[profile_index]);
		app->rkps[profile_index] = arvo_rkp_dup(rkp);
		arvo_dbus_emit_profile_data_changed_outside(app->dbus_proxy, profile_number);
		arvoconfig_profile_page_set_rkp(app->profile_pages[profile_index], rkp);
		return TRUE;
	}
}

static gboolean display_quit_dialog(ArvoconfigApplication *app) {
	guint i;
	gboolean modified;
	ArvoRkp *rkps[ARVO_PROFILE_NUM];
	gboolean retval;
	GError *error = NULL;

	modified = FALSE;
	for (i = 0; i < ARVO_PROFILE_NUM; ++i) {
		rkps[i] = arvoconfig_profile_page_get_rkp(app->profile_pages[i]);
		if (arvo_rkp_get_modified(rkps[i]))
			modified = TRUE;
	}
	if (!modified) {
		for (i = 0; i < ARVO_PROFILE_NUM; ++i)
			arvo_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 < ARVO_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 < ARVO_PROFILE_NUM; ++i)
		arvo_rkp_free(rkps[i]);

	return retval;
}

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

	return !display_quit_dialog(app);
}

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

static void save_profile_to_device_cb(ArvoconfigProfilePage *profile_page, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	ArvoRkp *rkp = arvoconfig_profile_page_get_rkp(profile_page);
	guint profile_index = arvoconfig_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);

	arvo_rkp_free(rkp);
}

static GtkFileFilter *windows_file_filter_new(void) {
	GtkFileFilter *filter;
	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "Arvo Windows profiles");
	gtk_file_filter_add_pattern(filter, "*.rkp");
	return filter;
}

static GtkFileFilter *linux_file_filter_new(void) {
	GtkFileFilter *filter;
	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "Arvo Linux profiles");
	gtk_file_filter_add_pattern(filter, "*.rkp");
	return filter;
}

static GtkFileFilter *all_file_filter_new(void) {
	GtkFileFilter *filter;
	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "All files");
	gtk_file_filter_add_pattern(filter, "*");
	return filter;
}

static void save_profile_to_file_cb(ArvoconfigProfilePage *profile_page, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	GtkFileFilter *windows_filter;
	GtkFileFilter *linux_filter;
	GtkFileFilter *all_filter;
	GtkFileFilter *filter;
	guint profile_index = arvoconfig_profile_page_get_index(profile_page);
	ArvoRkp *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);

	windows_filter = windows_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), windows_filter);
	linux_filter = linux_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), linux_filter);
	all_filter = all_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), all_filter);

	path = arvo_configuration_get_rkp_save_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) {
		filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog));
		filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
		path = g_path_get_dirname(filename);
		arvo_configuration_set_rkp_save_path(app->config, path);
		g_free(path);

		rkp = arvoconfig_profile_page_get_rkp(app->profile_pages[profile_index]);

		if (filter != linux_filter)
			arvo_linux_rkp_to_windows(rkp);

		arvo_rkp_write_with_path(filename, rkp, &error);
		arvo_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(ArvoconfigProfilePage *profile_page, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	GtkFileFilter *windows_filter;
	GtkFileFilter *linux_filter;
	GtkFileFilter *all_filter;
	GtkFileFilter *filter;
	ArvoRkp *rkp;
	guint profile_index = arvoconfig_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);

	windows_filter = windows_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), windows_filter);
	linux_filter = linux_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), linux_filter);
	all_filter = all_file_filter_new();
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), all_filter);

	path = arvo_configuration_get_rkp_save_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) {
		filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog));
		filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
		path = g_path_get_dirname(filename);
		arvo_configuration_set_rkp_save_path(app->config, path);
		g_free(path);

		rkp = arvo_rkp_read_with_path(filename, &error);
		
		if (filter != linux_filter)
			arvo_windows_rkp_to_linux(rkp);

		if (error) {
			roccat_warning_dialog(GTK_WINDOW(dialog), "Error loading rkp", error->message);
			g_error_free(error);
		} else {
			arvo_rkp_set_modified(rkp);
			arvoconfig_profile_page_set_rkp(app->profile_pages[profile_index], rkp);
			arvo_rkp_free(rkp);
		}

		g_free(filename);
	}

	gtk_widget_destroy(dialog);
}

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

	warn_if_no_device(app);
	for (i = 0; i < ARVO_PROFILE_NUM; ++i) {
		rkp = arvoconfig_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);

		arvo_rkp_free(rkp);
	}
}

static void edit_preferences_cb(GtkMenuItem *item, gpointer user_data) {
	ArvoconfigApplication *app = (ArvoconfigApplication *)user_data;
	arvoconfig_configuration_dialog(GTK_WINDOW(app->window), app->config);
	arvo_dbus_emit_configuration_changed_outside(app->dbus_proxy);
}

ArvoconfigApplication *arvoconfig_application_new(void) {
	ArvoconfigApplication *app;
	GtkWidget *tab_label;
	guint i;
	GtkMenuItem *preferences_menu;

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

	app->config = arvo_configuration_load();

	app->window = ROCCAT_CONFIG_WINDOW(roccat_config_window_new(ARVO_DEVICE_NAME));
	gtk_widget_show(GTK_WIDGET(app->window));

	for (i = 0; i < ARVO_PROFILE_NUM; ++i) {
		app->profile_pages[i] = ARVOCONFIG_PROFILE_PAGE(arvoconfig_profile_page_new(i));
		tab_label = arvoconfig_profile_page_get_tab_label(app->profile_pages[i]);
		roccat_config_window_append_page(app->window, GTK_WIDGET(app->profile_pages[i]), tab_label);

		app->rkps[i] = arvo_rkp_load_actual(i + 1);
		arvoconfig_profile_page_set_rkp(app->profile_pages[i], app->rkps[i]);

		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 = ARVOCONFIG_SETTINGS_PAGE(arvoconfig_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);

	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->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 = arvo_dbus_proxy_new();
	app->device_scanner = arvo_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 arvoconfig_application_free(ArvoconfigApplication *app) {
	guint i;

	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->arvo);
	app->arvo = NULL;

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

	arvoconfig_configuration_save(GTK_WINDOW(app->window), app->config);
	arvo_configuration_free(app->config);
	app->config = NULL;

	for (i = 0; i < ARVO_PROFILE_NUM; ++i)
		g_free(app->rkps[i]);

	g_free(app);
}
