/*
 * 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 "InputDeviceMouse.hpp"
#include "Base/Logger.hpp"

namespace OpenVulkano::Input
{
	void InputDeviceMouse::Init(const int index, const std::string& name)
	{
		InputDevice::Init(InputDeviceType::MOUSE, index, name);

		ClearAxes();
		pressedButtons = 0;
		lastPressedButtons = 0;
		mousePosX = 0;
		mousePosY = 0;
		lastWindow = nullptr;
	}

	void InputDeviceMouse::UpdateButtons(uint8_t newPressedButtons)
	{
		lastPressedButtons = pressedButtons;
		pressedButtons = newPressedButtons;
		if (lastPressedButtons != pressedButtons)
			Logger::INPUT->debug("Mouse button state changed {0:08b}", pressedButtons);
	}

	void InputDeviceMouse::UpdatePosition(double posX, double posY)
	{
		axes[InputKey::Mouse::AXIS_X] = static_cast<float>(posX - mousePosX);
		axes[InputKey::Mouse::AXIS_Y] = static_cast<float>(posY - mousePosY);
		mousePosX = posX;
		mousePosY = posY;
		Logger::INPUT->trace("Mouse moved posX: {0} posY: {1}, relativeX: {2}, relativeY: {3}", posX, posY, axes[InputKey::Mouse::AXIS_X], axes[InputKey::Mouse::AXIS_Y]);
	}

	void InputDeviceMouse::UpdateWheel(float wheelX, float wheelY)
	{
		axes[InputKey::Mouse::AXIS_WHEEL_X] = wheelX;
		axes[InputKey::Mouse::AXIS_WHEEL_Y] = wheelY;
		Logger::INPUT->debug("Mouse scrolled x: {0} y: {1}", wheelX, wheelY);
	}

	void InputDeviceMouse::UpdateActiveWindow(IWindow* window)
	{
		ClearAxes();
		lastWindow = window;
	}

	void InputDeviceMouse::ClearAxes()
	{
		for (float& axis : axes)
		{
			axis = 0;
		}
	}
}