/*
 * joystick plugin for VDR
 *
 * joystick.c - joystick remote class
 *
 * Copyright (C) 2003 Andreas Regel <andreas.regel@powarman.de>
 *
 * This code is distributed under the terms and conditions of the
 * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details.
 */

typedef signed int int32_t;
typedef signed long long int64_t;

#include <linux/joystick.h>

#include "joystick.h"
#include "mappings.h"
#include "setup.h"

cJoystickRemote::cJoystickRemote(void)
:	cRemote("Joystick")
{
	char numAxes;
	cMapping * mapping;
	char str[256];
	int i;

	fd = open(JoystickSetup.device, O_RDONLY);
	if (fd < 0)
	{
		esyslog("joystick: could not open device %s", JoystickSetup.device);
		fd = -1;
		return;
	}
	ioctl(fd, JSIOCGAXES, &numAxes);
	axes = new int[numAxes];
	for (i = 0; i < numAxes; i++)
	{
		axes[i] = -1;
		mapping = Mappings.GetByNumber(i);
		if (!mapping)
		{
			mapping = new cMapping();
			sprintf(str, "%d:0:20000:-25000:25000", i);
			if (mapping->Parse(str))
				Mappings.Add(mapping);
		}
	}
	Start();
}

cJoystickRemote::~cJoystickRemote()
{
	Cancel();
	delete[] axes;
}

void cJoystickRemote::Action(void)
{
	dsyslog("Joystick remote control thread started (pid=%d)", getpid());

	struct js_event e;
	char str[16];
	
	for (; fd >= 0;)
	{
		LOCK_THREAD;
		if (cFile::FileReady(fd, 100))
		{
			if (safe_read(fd, &e, sizeof(struct js_event)) == sizeof(struct js_event))
			{
				if (e.type & JS_EVENT_INIT)
				{
					// Ignore
				}
				else if (e.type & JS_EVENT_BUTTON)
				{
					if (e.value == 1)
					{
						sprintf(str, "Button%d", e.number);
						Put(str);
					}
				}
				else if (e.type & JS_EVENT_AXIS)
				{
					cMapping * mapping = Mappings.GetByNumber(e.number);
					if (mapping)
					{
						int newButton = mapping->GetButton(e.value, axes[e.number]);
						if (newButton != axes[e.number])
						{
							axes[e.number] = newButton;
							if (newButton != -1)
							{
								sprintf(str, "Axis%dButton%d", e.number, newButton);
								Put(str);
							}
						}
					}
				}
			}
			else
			{
				LOG_ERROR;
			}
		}
	}
	dsyslog("Joystick remote control thread ended (pid=%d)", getpid());
}

