/*
 * 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/pyra.h"
#include <stdlib.h>

static gchar const * const info_name = "info";
static gchar const * const firmware_version_name = "firmware_version";

static void pyra_info_finalize(PyraInfo *info) {
	info->command = PYRA_COMMAND_INFO;
	info->size = sizeof(PyraInfo);
}

static gboolean pyra_info_write(RoccatDevice *pyra, PyraInfo *info, GError **error) {
	pyra_info_finalize(info);
	return roccat_device_write(pyra, info_name, (gchar const *)info, sizeof(PyraInfo), error);
}

gboolean pyra_reset(RoccatDevice *pyra, GError **error) {
	PyraInfo info = {};
	info.firmware_version = PYRA_INFO_FUNCTION_RESET;
	return pyra_info_write(pyra, &info, error);
}

static guint pyra_firmware_version_read_fallback(RoccatDevice *pyra, GError **error) {
	guint result;
	gchar *string = roccat_device_read(pyra, firmware_version_name, 0, error);
	if (*error) return 0;
	result = strtoul(string, NULL, 10);
	g_free(string);
	return result;
}

guint pyra_firmware_version_read(RoccatDevice *pyra, GError **error) {
	PyraInfo *info;
	guint result;

	info = pyra_info_read(pyra, error);
	if (!info) {
		g_clear_error(error);
		return pyra_firmware_version_read_fallback(pyra, error);
	}
	result = info->firmware_version;
	g_free(info);
	return result;
}

gchar *pyra_firmware_version_to_string(guint firmware_version) {
	return g_strdup_printf("%i.%i", firmware_version / 100, firmware_version % 100);
}

static PyraInfo *pyra_info_read_fallback(RoccatDevice *pyra, GError **error) {
	PyraInfo *info;
	guint firmware_version;

	firmware_version = pyra_firmware_version_read_fallback(pyra, error);
	if (firmware_version == 0)
		return NULL;

	info = g_malloc0(sizeof(PyraInfo));
	info->firmware_version = firmware_version;
	pyra_info_finalize(info);
	return info;
}

PyraInfo *pyra_info_read(RoccatDevice *pyra, GError **error) {
	PyraInfo *info;

	info = (PyraInfo *)roccat_device_read(pyra, info_name, sizeof(PyraInfo), error);
	if (info)
		return info;

	g_clear_error(error);
	return pyra_info_read_fallback(pyra, error);
}
