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

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

static void koneplus_info_finalize(KoneplusInfo *info) {
	info->command = KONEPLUS_COMMAND_INFO;
	info->size = sizeof(KoneplusInfo);
}

static gboolean koneplus_info_write(RoccatDevice *koneplus, KoneplusInfo *info, GError **error) {
	koneplus_info_finalize(info);
	return roccat_device_write(koneplus, info_name, (gchar const *)info, sizeof(KoneplusInfo), error);
}

gboolean koneplus_reset(RoccatDevice *koneplus, GError **error) {
	KoneplusInfo info = { };
	info.firmware_version = KONEPLUS_INFO_FUNCTION_RESET;
	return koneplus_info_write(koneplus, &info, error);
}

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

guint koneplus_firmware_version_read(RoccatDevice *koneplus, GError **error) {
	KoneplusInfo *info;
	guint result;

	info = koneplus_info_read(koneplus, error);
	if (info) {
		result = info->firmware_version;
		g_free(info);
		return result;
	}

	g_clear_error(error);
	return koneplus_firmware_version_read_fallback(koneplus, error);
}

/* create fake KoneplusInfo */
static KoneplusInfo *koneplus_info_read_fallback(RoccatDevice *koneplus, GError **error) {
	KoneplusInfo *info;
	guint firmware_version;

	firmware_version = koneplus_firmware_version_read_fallback(koneplus, error);
	if (firmware_version == 0)
		return NULL;

	info = g_malloc0(sizeof(KoneplusInfo));
	info->firmware_version = firmware_version;
	koneplus_info_finalize(info);
	return info;
}

KoneplusInfo *koneplus_info_read(RoccatDevice *koneplus, GError **error) {
	KoneplusInfo *info;

	info = (KoneplusInfo *)roccat_device_read(koneplus, info_name, sizeof(KoneplusInfo), error);
	if (info)
		return info;

	g_clear_error(error);
	return koneplus_info_read_fallback(koneplus, error);
}

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