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

static gchar const * const startup_profile_name = "startup_profile";
static gchar const * const actual_profile_name = "actual_profile";

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

gboolean koneplus_actual_profile_write(RoccatDevice *koneplus, guint profile_number, GError **error) {
	gboolean retval = TRUE;
	gchar *string;
	GError *localerror = NULL;
	GError **errorpointer;

	g_assert(profile_number < KONEPLUS_PROFILE_NUM);

	errorpointer = error ? error : &localerror;

	string = g_strdup_printf("%i", profile_number);

	roccat_device_write(koneplus, actual_profile_name, string, strlen(string), errorpointer);

	if (*errorpointer) {
		if ((*errorpointer)->domain == G_FILE_ERROR && (*errorpointer)->code == G_FILE_ERROR_ACCES) { // Fallback
			g_clear_error(errorpointer);
			roccat_device_write(koneplus, startup_profile_name, string, strlen(string), errorpointer);

			if (*errorpointer)
				retval = FALSE;
		} else
			retval = FALSE;
	}

	g_free(string);

	if (localerror)
		g_error_free(localerror);

	return retval;
}
