/*
 * 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 <Python.h>
#include "ryos_ripple_python.h"
#include "ryos_custom_lights.h"
#include "ryos_light_control.h"
#include "g_roccat_helper.h"
#include "roccat_helper.h"
#include "config.h"
#include <gaminggear/threads.h>

#define RYOS_RIPPLE_PYTHON_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), RYOS_RIPPLE_PYTHON_TYPE, RyosRipplePythonClass))
#define IS_RYOS_RIPPLE_PYTHON_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), RYOS_RIPPLE_PYTHON_TYPE))

typedef struct _RyosRipplePythonClass RyosRipplePythonClass;

struct _RyosRipplePythonClass {
	GObjectClass parent_class;
};

enum {
	PROP_0,
	PROP_MODULE,
};

static RyosCustomLights custom_lights;
static RoccatDevice *device;
static GThread *thread;
static GaminggearMutex mutex;
static GaminggearCond start;
static gchar *module_name;
static PyObject *module;

static guint8 hid_to_bit[] = {
/*	   0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f */
	0xff, 0xff, 0xff, 0xff, 0x3d, 0x63, 0x62, 0x3e, 0x26, 0x4a, 0x3f, 0x4b, 0x35, 0x4c, 0x41, 0x42, /* 0 */
	0x4d, 0x58, 0x2a, 0x36, 0x25, 0x32, 0x49, 0x33, 0x40, 0x57, 0x31, 0x56, 0x34, 0x61, 0x0d, 0x19, /* 1 */
	0x1a, 0x1b, 0x27, 0x1c, 0x28, 0x1d, 0x29, 0x12, 0x44, 0x01, 0x2c, 0x24, 0x70, 0x1e, 0x13, 0x1f, /* 2 */
	0x2b, 0x38, 0x43, 0x4e, 0x37, 0x0c, 0x59, 0x5a, 0x4f, 0x3c, 0x02, 0x0e, 0x03, 0x0f, 0x04, 0x10, /* 3 */
	0x05, 0x11, 0x06, 0x07, 0x08, 0x14, 0x09, 0x15, 0x21, 0x2d, 0x39, 0x45, 0x51, 0x5d, 0x69, 0x76, /* 4 */
	0x68, 0x74, 0x75, 0x0a, 0x16, 0x0b, 0x17, 0x2f, 0x5f, 0x52, 0x5e, 0x53, 0x3a, 0x46, 0x3b, 0x22, /* 5 */
	0x2e, 0x23, 0x6a, 0x6b, 0x55, 0x67, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 6 */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 7 */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x5b, 0x71, 0x20, 0x65, 0x64, 0xff, 0xff, 0xff, 0xff, /* 8 */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 9 */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x18, 0x30, 0x48, 0x60, 0xff, /* a */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* b */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* c */
	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* d */
	0x6c, 0x54, 0x6e, 0x6d, 0x5c, 0x50, 0x72, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* e */
	0xff, 0x73, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* f */
};

static PyObject *ryos_set_key(PyObject *self, PyObject *args) {
	unsigned int hid;

	if (!PyArg_ParseTuple(args, "I", &hid)) {
		PyErr_Print();
		return NULL;
	}
	roccat_bitfield_set_bit(custom_lights.data, hid_to_bit[hid], TRUE);
	Py_RETURN_NONE;
}

static PyObject *ryos_get_key(PyObject *self, PyObject *args) {
	unsigned int value;
	unsigned int hid;

	if (!PyArg_ParseTuple(args, "I", &hid)) {
		PyErr_Print();
		return NULL;
	}
	value = roccat_bitfield_get_bit(custom_lights.data, hid_to_bit[hid]);
	return Py_BuildValue("I", value);
}

static PyObject *ryos_clear_key(PyObject *self, PyObject *args) {
	unsigned int hid;

	if (!PyArg_ParseTuple(args, "I", &hid)) {
		PyErr_Print();
		return NULL;
	}
	roccat_bitfield_set_bit(custom_lights.data, hid_to_bit[hid], FALSE);
	Py_RETURN_NONE;
}

static PyObject *ryos_clear(PyObject *self, PyObject *args) {
	if (!PyArg_ParseTuple(args, "")) {
		PyErr_Print();
		Py_RETURN_NONE; // FIXME exception
	}
	memset(custom_lights.data, 0, RYOS_CUSTOM_LIGHTS_DATA_LENGTH);
	Py_RETURN_NONE;
}

static PyObject *ryos_empty(PyObject *self, PyObject *args) {
	if (!PyArg_ParseTuple(args, "")) {
		PyErr_Print();
		Py_RETURN_FALSE; // FIXME exception
	}
	if (ryos_custom_lights_empty(&custom_lights))
		Py_RETURN_TRUE;
	else
		Py_RETURN_FALSE;
}

static PyMethodDef ryos_methods[] = {
	{"set_key", ryos_set_key, METH_VARARGS, ""},
	{"get_key", ryos_get_key, METH_VARARGS, ""},
	{"clear_key", ryos_clear_key, METH_VARARGS, ""},
	{"clear", ryos_clear, METH_VARARGS, ""},
	{"empty", ryos_empty, METH_VARARGS, ""},
	{NULL, NULL, 0, NULL}
};

static gboolean add_path(void) {
	PyObject *sys_path; // borrowed reference
	PyObject *path;
	int retval;

	sys_path = PySys_GetObject("path");
	if (!sys_path)
		return FALSE;

	path = PyString_FromString(RYOS_RIPPLE_MODULES_PATH);
	if (!path)
		return FALSE;

	retval = PyList_Append(sys_path, path);
	Py_DECREF(path);
	if (retval)
		return FALSE;

	return TRUE;
}

static gint python_call_tick(void) {
	PyObject *result;
	long value;

	result = PyObject_CallMethod(module, "Tick", NULL);

	if (result == NULL)
		goto error;

	if (result == Py_None) {
		Py_DECREF(result);
		return -1; // None
	}

	value = PyInt_AsLong(result);
	if (!PyErr_Occurred()) {
		Py_DECREF(result);
		return value; // Value
	}

	Py_DECREF(result);
error:
	PyErr_Print();
	g_debug("error");
	return -1; // Error
}

static void python_call_start(guint hid) {
	(void)PyObject_CallMethod(module, "Start", "I", hid);
}

static gpointer worker(gpointer user_data) {
	GError *local_error = NULL;
	RoccatDevice *local_device;
	gint msecs;

	while (TRUE) {
		gaminggear_mutex_lock(&mutex);
		gaminggear_cond_wait(&start, &mutex);
		local_device = device;
		gaminggear_mutex_unlock(&mutex);

		if (!ryos_light_control_custom(local_device, TRUE, &local_error)) {
			g_warning("ripple_thread: couldn't init custom: %s", local_error->message);
			g_clear_error(&local_error);
			continue; // Try again next time its started
		}

		while (TRUE) {
			gaminggear_mutex_lock(&mutex);
			msecs = python_call_tick();
			gaminggear_mutex_unlock(&mutex);

			if (msecs == -1)
				break;

			if (!ryos_custom_lights_write(local_device, &custom_lights, &local_error)) {
				g_warning("ripple_thread: couldn't write data: %s", local_error->message);
				g_clear_error(&local_error);
				break;
			}

			g_usleep(msecs * G_ROCCAT_USEC_PER_MSEC);
		}

		if (!ryos_light_control_custom(local_device, FALSE, &local_error)) {
			g_warning("ripple_thread: couldn't deinit custom: %s", local_error->message);
			g_clear_error(&local_error);
		}
	}

	return NULL;
}

static void ryos_ripple_python_start(RyosRipple *self, RoccatDevice *device_arg, guint hid) {
	gaminggear_mutex_lock(&mutex);
	device = device_arg;
	memset(&custom_lights.data, 0, RYOS_CUSTOM_LIGHTS_DATA_LENGTH);
	python_call_start(hid);
	gaminggear_cond_signal(&start);
	gaminggear_mutex_unlock(&mutex);
}

static void ryos_ripple_python_interface_init(RyosRippleInterface *iface) {
	iface->start = ryos_ripple_python_start;
}

G_DEFINE_TYPE_WITH_CODE(RyosRipplePython, ryos_ripple_python, G_TYPE_OBJECT,
		G_IMPLEMENT_INTERFACE(RYOS_RIPPLE_TYPE, ryos_ripple_python_interface_init));

RyosRipplePython *ryos_ripple_python_new(gchar const *module) {
	return RYOS_RIPPLE_PYTHON(g_object_new(RYOS_RIPPLE_PYTHON_TYPE,
			"module", module,
			NULL));
}

static void ryos_ripple_python_init(RyosRipplePython *ripple_python) {}

static GObject *ryos_ripple_python_constructor(GType gtype, guint n_properties, GObjectConstructParam *properties) {
	GError *local_error = NULL;
	GObject *obj;

	obj = G_OBJECT_CLASS(ryos_ripple_python_parent_class)->constructor(gtype, n_properties, properties);

	/* Python claims to not change the arg but wants it non-const.
	 * g_get_prgname() once returned 'char *', nowadays returns 'const char *'
	 */
	Py_SetProgramName((char *)g_get_prgname());
	Py_InitializeEx(0);
	Py_InitModule("ryos", ryos_methods);

	if (!add_path()) {
		PyErr_Print();
		goto out;
	}

	module = PyImport_ImportModule(module_name);
	if (!module) {
		PyErr_Print();
		goto out;
	}

	gaminggear_mutex_init(&mutex);
	gaminggear_cond_init(&start);
	thread = gaminggear_thread_try_new("RyosRipple", worker, NULL, &local_error);
	if (local_error) {
		g_warning("Can't create ripple thread: %s", local_error->message);
		g_clear_error(&local_error);
	}

out:
	return obj;
}

static void ryos_ripple_python_finalize(GObject *object) {
	if (thread)
		g_thread_join(thread);
	gaminggear_mutex_clear(&mutex);
	gaminggear_cond_clear(&start);

	if (module) {
		Py_DECREF(module);
	}
	g_free(module_name);

	Py_Finalize();

	G_OBJECT_CLASS(ryos_ripple_python_parent_class)->finalize(object);
}

static void ryos_ripple_python_set_property(GObject *object, guint prop_id, GValue const *value, GParamSpec *pspec) {
	switch(prop_id) {
	case PROP_MODULE:
		module_name = g_strdup(g_value_get_string(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
		break;
	}
}

static void ryos_ripple_python_class_init(RyosRipplePythonClass *klass) {
	GObjectClass *gobject_class;

	gobject_class = G_OBJECT_CLASS(klass);

	gobject_class->constructor = ryos_ripple_python_constructor;
	gobject_class->set_property = ryos_ripple_python_set_property;
	gobject_class->finalize = ryos_ripple_python_finalize;

	g_object_class_install_property(gobject_class, PROP_MODULE,
			g_param_spec_string("module",
					"Python module",
					"Python module",
					"ripple",
					G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
}
