/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "InputDeviceGLFW.hpp"
#include "Base/Logger.hpp"
#include <GLFW/glfw3.h>

namespace OpenVulkano::GLFW
{
	void ControllerGLFW::Init(int joystickId)
	{
		if (GetIndex() != -1) return;
		gamepad = glfwJoystickIsGamepad(joystickId);
		std::string name = glfwGetJoystickName(joystickId);
		if (gamepad) name += " - " + std::string(glfwGetGamepadName(joystickId));
		InputDeviceController::Init(joystickId, name);
		if (!gamepad) Logger::INPUT->warn("Joysticks are currently not supported");
	}

	void ControllerGLFW::Tick()
	{
		if (GetIndex() == -1) return;
		if (gamepad)
		{
			GLFWgamepadstate state;
			glfwGetGamepadState(GetIndex(), &state);
			for (int i = 0; i < 6; i++)
			{
				SetAxis(static_cast<Input::InputKey::Controller::Axis>(i), state.axes[i]);
			}

			uint32_t buttonStates = 0;
			for (int i = 0; i < 15; i++)
			{
				buttonStates |= static_cast<uint32_t>(state.buttons[i] != 0) << i;
			}
			SetButtons(buttonStates);
		}
		else
		{
			// Joysticks currently are not supported
		}
	}
}