#include "gamepad.h"
#include "GLFW/glfw3.h"
#include "error.h"
#include "string.h"

struct sw_gamepad sw_gamepads[SW_MAX_GAMEPADS];

void sw_gamepad_static_init() {
	memset(sw_gamepads, 0, sizeof(sw_gamepads));
}

void sw_gamepad_tick() {
#ifdef __EMSCRIPTEN__
	i32 i, j, count;
	const f32 *axes;
	const unsigned char *buttons;

	for(i = 0; i < SW_MAX_GAMEPADS; ++i) {
		if(glfwJoystickPresent(i)) {
			axes = glfwGetJoystickAxes(i, &count);
			count = i32_min(count, SW_MAX_GAMEPAD_AXES);

			for(j = 0; j < count; ++j) {
				sw_gamepads[i].axes[j] = axes[j];
			}

			buttons = glfwGetJoystickButtons(i, &count);
			count = i32_min(count, SW_MAX_GAMEPAD_BUTTONS);

			for(j = 0; j < SW_MAX_GAMEPAD_BUTTONS; ++j) {
				sw_gamepads[i].button_pressed[j] =
				    !sw_gamepads[i].button_pressed[j] && buttons[j];
				sw_gamepads[i].button_down[j] = buttons[j];
			}
		}
	}
#else  /* __EMSCRIPTEN__ */
	i32 i, j;
	GLFWgamepadstate state;

	for(i = 0; i < SW_MAX_GAMEPADS; ++i) {
		if(glfwGetGamepadState(i, &state)) {
			for(j = 0; j < SW_MAX_GAMEPAD_AXES; ++j) {
				sw_gamepads[i].axes[j] = state.axes[j];
			}
			for(j = 0; j < SW_MAX_GAMEPAD_BUTTONS; ++j) {
				bool down = state.buttons[j];
				sw_gamepads[i].button_pressed[j] =
				    !sw_gamepads[i].button_pressed[j] && down;
				sw_gamepads[i].button_down[j] = down;
			}
		}
	}
#endif /* __EMSCRIPTEN__ */
}
