#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#include "joystick_linux.h"

unsigned int js_version(int fd)
{
	uint32_t version;
	ioctl(fd, JSIOCGVERSION, &version);
	return version;
}

int js_buttons(int fd)
{
	uint8_t buttons;	
	ioctl(fd, JSIOCGBUTTONS, &buttons);
	return buttons;
}

int js_axes(int fd)
{
	uint8_t axes;	
	ioctl(fd, JSIOCGAXES, &axes);
	return axes;
}

int js_name(int fd, char* name, int len)
{
	return ioctl(fd, JSIOCGNAME(len), name);
}

int js_event_read(int fd, struct js_event *e)
{
	int c = read(fd, e, sizeof(*e));

	if (c == -1)
		return 0;
	if (c == sizeof(*e))
		return 1;
	return -1;
}

#if JOYSTICK_LINUX_MAIN
int main()
{
	int fd = open("/dev/input/js0", O_RDONLY | O_NONBLOCK);

	uint32_t version = js_version(fd);
	uint8_t buttons = js_buttons(fd);
	uint8_t axes = js_axes(fd);

	char name[256];
	js_name(fd, name, 256);

	printf("Name: %s\n", name);
	printf("Version: %u\t", version);
	printf("Buttons: %d\t", buttons);
	printf("Axes: %d\t", axes);

	for (;;) {
		struct js_event e;
		bool touched = false;
		while (js_event_read(fd, &e) == 1) {
			printf("Time: %d\t",   e.time);
			printf("Value: %d\t",  e.value);
			printf("Type: %d\t",   e.type);
			printf("Number: %d\n", e.number);
			touched = true;
		}
		if (touched)
			printf("\n");
		usleep(1000);
	}

	close(fd);
	return 0;
}
#endif