/*
 * 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 <unistd.h>

static gchar const * const tcu_name = "tcu";
static gchar const * const tcu_image_name = "tcu_image";

static gboolean koneplus_tcu_write(RoccatDevice *koneplus, KoneplusTcu *tcu, GError **error) {
	return roccat_device_write(koneplus, tcu_name, (gchar const *)tcu, sizeof(KoneplusTcu), error);
}

static KoneplusTcu *koneplus_tcu_read(RoccatDevice *koneplus, GError **error) {
	return (KoneplusTcu *)roccat_device_read(koneplus, tcu_name, sizeof(KoneplusTcu), error);
}

KoneplusTcuImage *koneplus_tcu_image_read(RoccatDevice *koneplus, GError **error) {
	return (KoneplusTcuImage *)roccat_device_read(koneplus, tcu_image_name, sizeof(KoneplusTcuImage), error);
}

static gboolean koneplus_tcu_write_struct(RoccatDevice *koneplus, guint8 action, guint8 reg, guint8 value, GError **error) {
	KoneplusTcu tcu;

	tcu.command = KONEPLUS_COMMAND_TCU;
	tcu.action = action;
	tcu.reg = reg;
	tcu.value = value;

	return koneplus_tcu_write(koneplus, &tcu, error);
}

gboolean koneplus_tcu_calibrate_step(RoccatDevice *koneplus, GError **error) {
	return koneplus_tcu_write_struct(koneplus, KONEPLUS_TCU_ACTION_FRAME_CAPTURE, 1, 0, error);
}

guint koneplus_tcu_image_get_median(KoneplusTcuImage const *image) {
	guint i;
	gulong sum = 0;
	for (i = 0; i < KONEPLUS_TCU_IMAGE_SIZE * KONEPLUS_TCU_IMAGE_SIZE; ++i)
		sum += image->data[i];

	return sum / (KONEPLUS_TCU_IMAGE_SIZE * KONEPLUS_TCU_IMAGE_SIZE);
}

gboolean koneplus_tcu_write_value(RoccatDevice *koneplus, guint8 reg, guint8 value, GError **error) {
	return koneplus_tcu_write_struct(koneplus, KONEPLUS_TCU_ACTION_WRITE, reg, value, error);
}

guint8 koneplus_tcu_read_value(RoccatDevice *koneplus, guint8 reg, GError **error) {
	KoneplusTcu *tcu;
	guint8 result;

	koneplus_tcu_write_struct(koneplus, KONEPLUS_TCU_ACTION_READ, reg, 0, error);
	if (*error)
		return 0;

	tcu = koneplus_tcu_read(koneplus, error);
	if (*error)
		return 0;
	result = tcu->value;
	g_free(tcu);

	return result;
}
