/*
 * 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 "roccat/savu.h"
#include "dbus_roccat_helper.h"
#include "config.h"
#include <stdlib.h>
#include <string.h>

static gboolean parameter_just_print_path = FALSE;
static gboolean parameter_just_print_version = FALSE;
static gboolean parameter_just_print_actual_profile = FALSE;
static gboolean parameter_just_reset = FALSE;
static gboolean parameter_read_firmware = FALSE;
static gint parameter_activate_profile = -1;
static gint parameter_load = -1;
static gint parameter_save = -1;
static gchar *parameter_in_rmp = NULL;
static gchar *parameter_out_rmp = NULL;
static gint parameter_sensor_register = -1;
static gboolean parameter_sensor_read = FALSE;
static gint parameter_sensor_write = -1;

static GOptionEntry entries[] = {
	{ "activate-profile", 'a', 0, G_OPTION_ARG_INT, &parameter_activate_profile, "activate profile NUMBER", "NUMBER" },
	{ "read-firmware", 'f', 0, G_OPTION_ARG_NONE, &parameter_read_firmware, "read firmware", NULL },
	{ "load", 'l', 0, G_OPTION_ARG_INT, &parameter_load, "load profile NUMBER", "NUMBER" },
	{ "path", 'p', 0, G_OPTION_ARG_NONE, &parameter_just_print_path, "print path in sysfs", NULL },
	{ "read-rmp", 'r', 0, G_OPTION_ARG_FILENAME, &parameter_in_rmp, "read from rmp-file FILENAME", "FILENAME" },
	{ "save", 's', 0, G_OPTION_ARG_INT, &parameter_save, "save as profile NUMBER", "NUMBER" },
	{ "version", 'v', 0, G_OPTION_ARG_NONE, &parameter_just_print_version, "print version", NULL },
	{ "write-rmp", 'w', 0, G_OPTION_ARG_FILENAME, &parameter_out_rmp, "write to rmp-file FILENAME", "FILENAME" },
	{ "actual-profile", 0, 0, G_OPTION_ARG_NONE, &parameter_just_print_actual_profile, "print actual profile", NULL },
	{ "reset", 0, 0, G_OPTION_ARG_NONE, &parameter_just_reset, "reset to factory defaults", NULL },
	{ "sensor-register", 0, 0, G_OPTION_ARG_INT, &parameter_sensor_register, "sensor register", NULL },
	{ "sensor-read", 0, 0, G_OPTION_ARG_NONE, &parameter_sensor_read, "read value from sensor register", NULL },
	{ "sensor-write", 0, 0, G_OPTION_ARG_INT, &parameter_sensor_write, "write VALUE to sensor register", "VALUE" },
	{ NULL }
};

static gboolean parse_profile_number_parameter(gint number, GError **error) {
	if (number < 1 || number > SAVU_PROFILE_NUM) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "profile numbers have to be in range of 1-5");
		return FALSE;
	}
	return TRUE;
}

static gboolean post_parse_func(GOptionContext *context, GOptionGroup *group, gpointer data, GError **error) {
	guint just_counter = 0;

	if (parameter_just_print_path) ++just_counter;
	if (parameter_just_print_version) ++just_counter;
	if (parameter_just_print_actual_profile) ++just_counter;
	if (parameter_just_reset) ++just_counter;
	if (just_counter > 1) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "just give one of -p, -v, --actual-profile, --reset");
		return FALSE;
	}

	if (parameter_activate_profile != -1 && !parse_profile_number_parameter(parameter_activate_profile, error))
		return FALSE;

	if (parameter_load != -1 && !parse_profile_number_parameter(parameter_load, error))
		return FALSE;

	if (parameter_save != -1 && !parse_profile_number_parameter(parameter_save, error))
		return FALSE;

	if ((parameter_load != -1 || parameter_in_rmp) && !(parameter_out_rmp || parameter_save != -1)) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "if -r or -l is given, -w or -s is needed");
		return FALSE;
	}

	if (parameter_load != -1 && parameter_in_rmp) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "-r and -l are mutual exclusive");
		return FALSE;
	}

	if (parameter_sensor_register != -1 && (parameter_sensor_register < 0 || parameter_sensor_register > 255)) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "sensor register out of range [0-255]");
		return FALSE;
	}

	if (parameter_sensor_write != -1 && (parameter_sensor_write < 0 || parameter_sensor_write > 255)) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "sensor value out of range [0-255]");
		return FALSE;
	}

	if ((parameter_sensor_read || parameter_sensor_write != -1) && !(parameter_sensor_register != -1)) {
		g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED, "if --sensor-read or --sensor-write is given, --sensor-register is needed");
		return FALSE;
	}

	return TRUE;
}

static GOptionContext *commandline_parse(int *argc, char ***argv) {
	GOptionContext *context = NULL;
	GError *error = NULL;

	context = g_option_context_new("- control extended capabilities of Roccat Savu mouse");
	g_option_context_add_main_entries(context, entries, NULL);

	g_option_group_set_parse_hooks(g_option_context_get_main_group(context), NULL, post_parse_func);

	if (!g_option_context_parse(context, argc, argv, &error)) {
		g_critical("option parsing failed: %s", error->message);
		exit(EXIT_FAILURE);
	}
	return context;
}

static void commandline_free(GOptionContext *context) {
	g_free(parameter_in_rmp);
	g_free(parameter_out_rmp);
	g_option_context_free(context);
}

static gboolean print_actual_profile(RoccatDevice *savu, GError **error) {
	guint profile_index = savu_profile_read(savu, error);
	if (*error)
		return FALSE;
	g_print("%i\n", profile_index + 1);
	return TRUE;
}

static gboolean print_firmware(RoccatDevice *savu, GError **error) {
	guint firmware_version;
	gchar *firmware_string;

	firmware_version = savu_firmware_version_read(savu, error);
	if (*error)
		return FALSE;

	firmware_string = savu_firmware_version_to_string(firmware_version);
	g_print("%s\n", firmware_string);
	g_free(firmware_string);

	return TRUE;
}

static gboolean print_sensor_value(RoccatDevice *savu, GError **error) {
	guint8 value;
	value = savu_sensor_read_value(savu, parameter_sensor_register, error);
	if (*error)
		return FALSE;
	g_print("%i\n", value);
	return TRUE;
}

static gboolean reset(RoccatDevice *savu, GError **error) {
	DBusGProxy *proxy;
	guint i;

	if (!savu_reset(savu, error))
		return FALSE;

	proxy = savu_dbus_proxy_new();
	if (!proxy)
		return TRUE;

	for (i = 0; i < SAVU_PROFILE_NUM; ++i)
		savu_dbus_emit_profile_data_changed_outside(proxy, i + 1);
	dbus_roccat_proxy_free(proxy);

	return TRUE;
}

int main(int argc, char **argv) {
	GOptionContext *context;
	RoccatDevice *savu;
	GError *error = NULL;
	int retval = EXIT_SUCCESS;
	SavuRmp *rmp = NULL;

	roccat_secure();

	context = commandline_parse(&argc, &argv);

	if (parameter_just_print_version) {
		g_print(VERSION_STRING "\n");
		goto exit1;
	}

#if !(GLIB_CHECK_VERSION(2, 36, 0))
	g_type_init();
#endif

	savu = savu_device_first();
	if (savu == NULL) {
		g_critical("No Savu found.");
		retval = EXIT_FAILURE;
		goto exit1;
	}

	if (parameter_just_print_path) {
		g_print("%s", roccat_device_get_syspath(savu));
		goto exit2;
	}

	if (parameter_just_print_actual_profile) {
		if (!print_actual_profile(savu, &error)) {
			g_critical("print actual profile failed: %s", error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_just_reset) {
		if (!reset(savu, &error)) {
			g_critical("reset failed: %s", error->message);
			retval = EXIT_FAILURE;
		}
		goto exit2;
	}

	if (parameter_read_firmware) {
		if (!print_firmware(savu, &error)) {
			g_critical("Print firmware version failed: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_sensor_read) {
		if (!print_sensor_value(savu, &error)) {
			g_critical("Reading sensor value failed: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_sensor_write != -1) {
		savu_sensor_write_value(savu, parameter_sensor_register, parameter_sensor_write, &error);
		if (error) {
			g_critical("Writing sensor value failed: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	}

	if (parameter_load != -1) {
		rmp = savu_rmp_load(savu, parameter_load - 1, &error);
		if (!rmp) {
			g_critical("Error loading profile %i: %s", parameter_load, error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	} else if (parameter_in_rmp) {
		rmp = savu_rmp_read_with_path(parameter_in_rmp, &error);
		if (!rmp) {
			g_critical("Error reading rmp: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit2;
		}
	} else
		rmp = savu_default_rmp();

	if (parameter_save != -1) {
		if (!savu_rmp_save(savu, rmp, parameter_save - 1, &error)) {
			g_critical("Error saving profile %i: %s", parameter_load, error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
		savu_dbus_emit_profile_data_changed_outside_instant(parameter_save);
	}

	if (parameter_out_rmp) {
		if (!savu_rmp_write_with_path(parameter_out_rmp, rmp, &error)) {
			g_critical("Error writing rmp: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
	}

	if (parameter_activate_profile != -1) {
		if (!savu_profile_write(savu, parameter_activate_profile -1, &error)) {
			g_critical("Error activating profile: %s", error->message);
			retval = EXIT_FAILURE;
			goto exit3;
		}
		savu_dbus_emit_profile_changed_outside_instant(parameter_activate_profile);
	}

exit3:
	savu_rmp_free(rmp);
exit2:
	roccat_device_free(savu);
exit1:
	commandline_free(context);
	g_clear_error(&error);
	exit(retval);
}
