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

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

KovaplusInfo *kovaplus_info_read(RoccatDevice *kovaplus, GError **error) {
	return (KovaplusInfo *)roccat_device_read(kovaplus, info_name, sizeof(KovaplusInfo), error);
}

static void kovaplus_info_finalize(KovaplusInfo *info) {
	info->command = KOVAPLUS_COMMAND_INFO;
	info->size = sizeof(KovaplusInfo);
}

static gboolean kovaplus_info_write(RoccatDevice *kovaplus, KovaplusInfo *info, GError **error) {
	kovaplus_info_finalize(info);
	return roccat_device_write(kovaplus, info_name, (gchar const *)info, sizeof(KovaplusInfo), error);
}

gboolean kovaplus_reset(RoccatDevice *kovaplus, GError **error) {
	KovaplusInfo info = {};
	info.firmware_version = KOVAPLUS_INFO_FUNCTION_RESET;
	return kovaplus_info_write(kovaplus, &info, error);
}

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

guint kovaplus_firmware_version_read(RoccatDevice *kovaplus, GError **error) {
	KovaplusInfo *info;
	guint result;

	info = kovaplus_info_read(kovaplus, error);
	if (!info) {
		g_clear_error(error);
		return kovaplus_firmware_version_read_fallback(kovaplus, error);
	}
	result = info->firmware_version;
	g_free(info);
	return result;
}

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