/*
 * 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 "savuconfig_application.h"
#include "roccat_config_window.h"
#include "savuconfig_configuration_dialog.h"
#include "savuconfig_profile_page.h"
#include "savuconfig_settings_page.h"
#include "roccat_warning_dialog.h"
#include "roccat_sensor_register_dialog.h"
#include "roccat_save_dialog.h"
#include "roccat_text_dialog.h"
#include "dbus_roccat_helper.h"

struct _SavuconfigApplication {
	RoccatDevice *savu;
	RoccatDeviceScanner *device_scanner;
	RoccatConfigWindow *window;
	SavuconfigProfilePage *profile_pages[SAVU_PROFILE_NUM];
	SavuconfigSettingsPage *settings_page;
	RoccatKeyFile *config;
	DBusGProxy *dbus_proxy;
	guint actual_profile_index;
};

static gboolean warn_if_no_device(SavuconfigApplication *app) {
	return roccat_no_device_warning_dialog(GTK_WINDOW(app->window), app->savu, SAVU_DEVICE_NAME);
}

static void settings_page_actual_profile_changed_cb(SavuconfigSettingsPage *settings_page, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	guint profile_number = savuconfig_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;
		savu_profile_write(app->savu, profile_index, &local_error);
		if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error activating profile", &local_error))
			return;
		savu_dbus_emit_profile_changed_outside(app->dbus_proxy, profile_number);
	}
}

static void device_reset_cb(SavuconfigSettingsPage *settings_page, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	SavuRmp *rmp;
	guint i;
	GError *error = NULL;

	if (!warn_if_no_device(app))
		return;

	savu_reset(app->savu, &error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error resetting device", &error))
		return;

	for (i = 0; i < SAVU_PROFILE_NUM; ++i) {
		rmp = savu_rmp_load_save_after_reset(app->savu, i, &error);
		savuconfig_profile_page_set_rmp(app->profile_pages[i], rmp);
		savu_rmp_free(rmp);
		savu_dbus_emit_profile_data_changed_outside(app->dbus_proxy, i + 1);
	}
}

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

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

static gboolean settings_page_set_info(SavuconfigApplication *app) {
	GError *local_error = NULL;
	SavuInfo *info;

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

static gboolean add_cb(RoccatDevice *device, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	GError *error = NULL;
	guint i;
	SavuRmp *rmp;

	if (app->savu) {
		roccat_multiple_device_warning_dialog(GTK_WINDOW(app->window), SAVU_DEVICE_NAME);
		return TRUE;
	}

	app->savu = device;

	app->actual_profile_index = savu_profile_read(app->savu, &error);
	if (!roccat_handle_error_dialog(GTK_WINDOW(app->window), "Can't read actual profile:", &error))
		goto error;
	savuconfig_settings_page_set_actual_profile(app->settings_page, app->actual_profile_index + 1);

	if (!settings_page_set_info(app))
		goto error;

	for (i = 0; i < SAVU_PROFILE_NUM; ++i) {
		rmp = savuconfig_profile_page_get_rmp(app->profile_pages[i]);
		savu_rmp_update_from_device(app->savu, rmp, i);
		savuconfig_profile_page_set_rmp(app->profile_pages[i], rmp);
		savu_rmp_free(rmp);
	}

	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, SAVU_DEVICE_NAME);

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

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

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

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

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

	return TRUE;
}

static gboolean save_unsaved(SavuconfigApplication *app, SavuRmp *rmp, guint profile_index, GError **error) {
	guint profile_number = profile_index + 1;

	if (app->savu)
		savu_rmp_save(app->savu, rmp, profile_index, error);
	else
		savu_rmp_save_actual(rmp, profile_index, error);

	if (*error)
		return FALSE;
	else {
		savu_dbus_emit_profile_data_changed_outside(app->dbus_proxy, profile_number);
		savuconfig_profile_page_set_rmp(app->profile_pages[profile_index], rmp);
		return TRUE;
	}
}

static gboolean display_quit_dialog(SavuconfigApplication *app) {
	guint i;
	gboolean modified;
	SavuRmp *rmps[SAVU_PROFILE_NUM];
	gboolean retval;
	GError *error = NULL;

	modified = FALSE;
	for (i = 0; i < SAVU_PROFILE_NUM; ++i) {
		rmps[i] = savuconfig_profile_page_get_rmp(app->profile_pages[i]);
		if (savu_rmp_get_modified(rmps[i]))
			modified = TRUE;
	}
	if (!modified) {
		for (i = 0; i < SAVU_PROFILE_NUM; ++i)
			savu_rmp_free(rmps[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 < SAVU_PROFILE_NUM; ++i) {
			if (!save_unsaved(app, rmps[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 < SAVU_PROFILE_NUM; ++i)
		savu_rmp_free(rmps[i]);

	return retval;
}

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

	return !display_quit_dialog(app);
}

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

static void save_profile_to_device_cb(SavuconfigProfilePage *profile_page, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	SavuRmp *rmp = savuconfig_profile_page_get_rmp(profile_page);
	guint profile_index = savuconfig_profile_page_get_index(profile_page);
	GError *error = NULL;

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

	savu_rmp_free(rmp);
}

static void add_file_filter_to_file_chooser(GtkFileChooser *chooser) {
	GtkFileFilter *filter;
	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "Savu Windows profiles");
	gtk_file_filter_add_pattern(filter, "*.rmp");
	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(SavuconfigProfilePage *profile_page, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	guint profile_index = savuconfig_profile_page_get_index(profile_page);
	SavuRmp *rmp;

	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 = savu_configuration_get_rmp_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);
		savu_configuration_set_rmp_path(app->config, path);
		g_free(path);

		rmp = savuconfig_profile_page_get_rmp(app->profile_pages[profile_index]);
		savu_rmp_write_with_path(filename, rmp, &error);
		savu_rmp_free(rmp);
		if (error) {
			roccat_warning_dialog(GTK_WINDOW(dialog), "Error saving rmp", error->message);
			g_error_free(error);
		}

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

static void load_profile_from_file_cb(SavuconfigProfilePage *profile_page, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	GtkWidget *dialog;
	gchar *filename, *path;
	GError *error = NULL;
	SavuRmp *rmp;
	guint profile_index = savuconfig_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 = savu_configuration_get_rmp_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);
		savu_configuration_set_rmp_path(app->config, path);
		g_free(path);

		rmp = savu_rmp_read_with_path(filename, &error);
		if (error) {
			roccat_warning_dialog(GTK_WINDOW(dialog), "Error loading rmp", error->message);
			g_error_free(error);
		} else {
			savu_rmp_set_modified(rmp);
			savuconfig_profile_page_set_rmp(app->profile_pages[profile_index], rmp);
			savu_rmp_free(rmp);
		}

		g_free(filename);
	}

	gtk_widget_destroy(dialog);
}

static void save_all_cb(GtkMenuItem *item, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	SavuRmp *rmp;
	guint i;
	GError *error = NULL;

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

		savu_rmp_free(rmp);
	}
}

static void sensor_read_cb(RoccatSensorRegisterDialog *dialog, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	guint reg = roccat_sensor_register_dialog_get_register(dialog);
	guint value;
	GError *error = NULL;

	value = savu_sensor_read_value(app->savu, reg, &error);
	if (roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error reading sensor register", &error))
		roccat_sensor_register_dialog_set_value(dialog, value);
}

static void sensor_write_cb(RoccatSensorRegisterDialog *dialog, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	guint reg = roccat_sensor_register_dialog_get_register(dialog);
	guint value = roccat_sensor_register_dialog_get_value(dialog);
	GError *error = NULL;
	savu_sensor_write_value(app->savu, reg, value, &error);
	roccat_handle_error_dialog(GTK_WINDOW(app->window), "Error writing sensor register", &error);
}

static void edit_sensor_cb(GtkMenuItem *item, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	RoccatSensorRegisterDialog *dialog;

	if (!warn_if_no_device(app))
		return;

	dialog = ROCCAT_SENSOR_REGISTER_DIALOG(roccat_sensor_register_dialog_new(GTK_WINDOW(app->window)));
	g_signal_connect(G_OBJECT(dialog), "read", G_CALLBACK(sensor_read_cb), app);
	g_signal_connect(G_OBJECT(dialog), "write", G_CALLBACK(sensor_write_cb), app);
	(void)gtk_dialog_run(GTK_DIALOG(dialog));
	gtk_widget_destroy(GTK_WIDGET(dialog));
}

static void edit_preferences_cb(GtkMenuItem *item, gpointer user_data) {
	SavuconfigApplication *app = (SavuconfigApplication *)user_data;
	savuconfig_configuration_dialog(GTK_WINDOW(app->window), app->config);
	savu_dbus_emit_configuration_changed_outside(app->dbus_proxy);
}

SavuconfigApplication *savuconfig_application_new(void) {
	SavuconfigApplication *app;
	SavuRmp *rmp;
	GtkWidget *tab_label;
	guint i;
	GtkMenuItem *preferences_menu;
	GtkMenuItem *sensor_menu_item;

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

	app->config = savu_configuration_load();

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

	for (i = 0; i < SAVU_PROFILE_NUM; ++i) {
		app->profile_pages[i] = SAVUCONFIG_PROFILE_PAGE(savuconfig_profile_page_new(i));
		tab_label = savuconfig_profile_page_get_tab_label(app->profile_pages[i]);
		roccat_config_window_append_page(app->window, GTK_WIDGET(app->profile_pages[i]), tab_label);

		rmp = savu_rmp_load_actual(i);
		savuconfig_profile_page_set_rmp(app->profile_pages[i], rmp);
		savu_rmp_free(rmp);

		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 = SAVUCONFIG_SETTINGS_PAGE(savuconfig_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);

	sensor_menu_item = GTK_MENU_ITEM(gtk_image_menu_item_new_with_label("Sensor register"));
	g_signal_connect(G_OBJECT(sensor_menu_item), "activate", G_CALLBACK(edit_sensor_cb), app);
	roccat_config_window_edit_menu_append(app->window, sensor_menu_item);

	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 = savu_dbus_proxy_new();
	app->device_scanner = savu_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 savuconfig_application_free(SavuconfigApplication *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->savu);
	app->savu = NULL;

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

	savuconfig_configuration_save(GTK_WINDOW(app->window), app->config);
	savu_configuration_free(app->config);
	app->config = NULL;

	g_free(app);
}
