/*
 * 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 "ryos_eventhandler_channel.h"
#include "g_cclosure_roccat_marshaller.h"
#include "roccat/ryos.h"
#include <sys/ioctl.h>

#define RYOS_EVENTHANDLER_CHANNEL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), RYOS_EVENTHANDLER_CHANNEL_TYPE, RyosEventhandlerChannelClass))
#define IS_RYOS_EVENTHANDLER_CHANNEL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), RYOS_EVENTHANDLER_CHANNEL_TYPE))
#define RYOS_EVENTHANDLER_CHANNEL_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), RYOS_EVENTHANDLER_CHANNEL_TYPE, RyosEventhandlerChannelPrivate))

typedef struct _RyosEventhandlerChannelClass RyosEventhandlerChannelClass;
typedef struct _RyosEventhandlerChannelPrivate RyosEventhandlerChannelPrivate;

struct _RyosEventhandlerChannel {
	GObject parent;
	RyosEventhandlerChannelPrivate *priv;
};

struct _RyosEventhandlerChannelClass {
	GObjectClass parent_class;
};

struct _RyosEventhandlerChannelPrivate {
	guint event_source_id;
	gint report_size;
	gboolean running;
};

enum {
	LIGHT_CHANGED, /* brightness_index */
	LIVE_RECORDING, /* key_index, event */
	OPEN_DRIVER,
	PROFILE_CHANGED, /* profile_index */
	QUICKLAUNCH, /* key_index */
	RIPPLE, /* hid */
	TALK, /* key_type, event */
	TIMER_START, /* key_index */
	TIMER_STOP,
	LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

G_DEFINE_TYPE(RyosEventhandlerChannel, ryos_eventhandler_channel, G_TYPE_OBJECT);

static void process_chrdev_event(RyosEventhandlerChannel *eventhandler_channel, RyosChrdevEvent const *event) {
	switch (event->special) {
	case RYOS_CHRDEV_EVENT_SPECIAL_RIPPLE:
		if (event->action == RYOS_CHRDEV_EVENT_RIPPLE_ACTION_PRESS)
			g_signal_emit((gpointer)eventhandler_channel, signals[RIPPLE], 0, event->data);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_PROFILE_START:
	case RYOS_CHRDEV_EVENT_SPECIAL_MULTIMEDIA:
		/* do nothing */
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_BACKLIGHT:
		g_signal_emit((gpointer)eventhandler_channel, signals[LIGHT_CHANGED], 0, event->data);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_PROFILE:
		g_signal_emit((gpointer)eventhandler_channel, signals[PROFILE_CHANGED], 0, event->data);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_LIVE_RECORDING:
		g_signal_emit((gpointer)eventhandler_channel, signals[LIVE_RECORDING], 0, event->data, event->action);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_QUICKLAUNCH:
		if (event->action == RYOS_CHRDEV_EVENT_ACTION_PRESS)
			g_signal_emit((gpointer)eventhandler_channel, signals[QUICKLAUNCH], 0, event->data);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_OPEN_DRIVER:
		g_signal_emit((gpointer)eventhandler_channel, signals[OPEN_DRIVER], 0);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_TIMER_START:
		if (event->action == RYOS_CHRDEV_EVENT_ACTION_PRESS)
			g_signal_emit((gpointer)eventhandler_channel, signals[TIMER_START], 0, event->data);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_TIMER_STOP:
		if (event->action == RYOS_CHRDEV_EVENT_ACTION_PRESS)
			g_signal_emit((gpointer)eventhandler_channel, signals[TIMER_STOP], 0);
		break;
	case RYOS_CHRDEV_EVENT_SPECIAL_TALK:
		g_signal_emit((gpointer)eventhandler_channel, signals[TALK], 0, event->data, event->action);
		break;
	default:
		g_message("eventhandler: unknown event = %02x%02x%02x", event->special, event->data, event->action);
	}
}

static gboolean io_cb(GIOChannel *channel, GIOCondition condition, gpointer user_data) {
	RyosEventhandlerChannel *eventhandler_channel = RYOS_EVENTHANDLER_CHANNEL(user_data);
	RyosEventhandlerChannelPrivate *priv = eventhandler_channel->priv;
	GIOStatus status;
	GError *error = NULL;
	gsize length;
	RyosChrdevEvent *event;

	if (condition & G_IO_HUP)
		return FALSE;

	event = g_malloc(priv->report_size);

	status = g_io_channel_read_chars(channel, (gchar *)event, priv->report_size, &length, &error);

	if (status == G_IO_STATUS_AGAIN)
		goto ok;

	if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF) {
		g_critical("error reading io_channel");
		goto error;
	}

	if (length != priv->report_size) {
		g_critical("wrong length %zd %s", length, error->message);
		goto error;
	}

	switch (priv->report_size) {
	case sizeof(RyosChrdevEvent):
		switch (event->type) {
		case RYOS_CHRDEV_EVENT_TYPE_SPECIAL:
			process_chrdev_event(eventhandler_channel, event);
			break;
		case RYOS_CHRDEV_EVENT_TYPE_RAD_W:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_A:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_S:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_D:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_THUMBSTER1:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_THUMBSTER2:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_THUMBSTER3:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_EASYSHIFT:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_MULTIMEDIA:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_M1:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_M2:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_M3:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_M4:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_M5:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_MACRO_SHORTCUT:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_TALK:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_MACRO_LIFE_REC:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_BACKLIGHT:
		case RYOS_CHRDEV_EVENT_TYPE_RAD_TOTAL:
			// TODO maybe handle rad events
			break;
		default:
			g_message("eventhandler: unknown event-type = %02x%02x%02x%02x", event->type, event->special, event->data, event->action);
			break;
		}
		break;
	default:
		g_message("eventhandler: wrong event size %u", priv->report_size);
		goto error;
	}

ok:
	g_free(event);
	return TRUE; // keep on going
error:
	g_free(event);
	return FALSE;
}

RyosEventhandlerChannel *ryos_eventhandler_channel_new(void) {
	return RYOS_EVENTHANDLER_CHANNEL(g_object_new(RYOS_EVENTHANDLER_CHANNEL_TYPE, NULL));
}

static void ryos_eventhandler_channel_init(RyosEventhandlerChannel *channel) {
	RyosEventhandlerChannelPrivate *priv = RYOS_EVENTHANDLER_CHANNEL_GET_PRIVATE(channel);
	channel->priv = priv;
	priv->running = FALSE;
}

gboolean ryos_eventhandler_channel_start(RyosEventhandlerChannel *eventhandler_channel, gchar const *path, GError **error) {
	RyosEventhandlerChannelPrivate *priv = eventhandler_channel->priv;
	GIOChannel *channel;
	GIOStatus status;
	int fd;

	channel = g_io_channel_new_file(path, "r", error);
	if (!channel)
		return FALSE;

	status = g_io_channel_set_encoding(channel, NULL, error);
	if (status != G_IO_STATUS_NORMAL) {
		g_io_channel_unref(channel);
		return FALSE;
	}

	fd = g_io_channel_unix_get_fd(channel);
	if (ioctl(fd, ROCCATIOCGREPSIZE, &priv->report_size) == -1)
		priv->report_size = sizeof(RyosChrdevEvent);

	if (priv->report_size != sizeof(RyosChrdevEvent)) {
		g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_FAILED, "ioctl reported unsupported event size %i", priv->report_size);
		g_io_channel_unref(channel);
		return FALSE;
	}

	priv->event_source_id = g_io_add_watch(channel, G_IO_IN | G_IO_HUP, (GIOFunc)io_cb, eventhandler_channel);
	/* g_io_add_watch increases reference count
	 * this passes ownership of the channel to the watch */
	g_io_channel_unref(channel);

	return TRUE;
}

void ryos_eventhandler_channel_stop(RyosEventhandlerChannel *eventhandler_channel) {
	RyosEventhandlerChannelPrivate *priv = eventhandler_channel->priv;
	if (priv->running) {
		g_source_remove(priv->event_source_id);
		priv->running = FALSE;
	}
}

static void finalize(GObject *object) {
	RyosEventhandlerChannel *eventhandler_channel = RYOS_EVENTHANDLER_CHANNEL(object);
	ryos_eventhandler_channel_stop(eventhandler_channel);
	G_OBJECT_CLASS(ryos_eventhandler_channel_parent_class)->finalize(object);
}

static void ryos_eventhandler_channel_class_init(RyosEventhandlerChannelClass *klass) {
	GObjectClass *gobject_class;

	gobject_class = (GObjectClass *)klass;

	gobject_class->finalize = finalize;

	g_type_class_add_private(klass, sizeof(RyosEventhandlerChannelPrivate));

	signals[LIGHT_CHANGED] = g_signal_new("light-changed", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__UCHAR, G_TYPE_NONE,
			1, G_TYPE_UCHAR);

	signals[LIVE_RECORDING] = g_signal_new("live-recording", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_roccat_marshal_VOID__UCHAR_UCHAR, G_TYPE_NONE,
			2, G_TYPE_UCHAR, G_TYPE_UCHAR);

	signals[OPEN_DRIVER] = g_signal_new("open-driver", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
			0);

	signals[PROFILE_CHANGED] = g_signal_new("profile-changed", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__UCHAR, G_TYPE_NONE,
			1, G_TYPE_UCHAR);

	signals[QUICKLAUNCH] = g_signal_new("quicklaunch", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__UCHAR, G_TYPE_NONE,
			1, G_TYPE_UCHAR);

	signals[RIPPLE] = g_signal_new("ripple", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__UCHAR, G_TYPE_NONE,
			1, G_TYPE_UCHAR);

	signals[TALK] = g_signal_new("talk", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_roccat_marshal_VOID__UCHAR_UCHAR, G_TYPE_NONE,
			2, G_TYPE_UCHAR, G_TYPE_UCHAR);

	signals[TIMER_START] = g_signal_new("timer-start", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__UCHAR, G_TYPE_NONE,
			1, G_TYPE_UCHAR);

	signals[TIMER_STOP] = g_signal_new("timer-stop", RYOS_EVENTHANDLER_CHANNEL_TYPE,
			G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
			0, NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
			0);
}
