//
// Created by sebastian on 07.02.26.
//

#include "InputManager.h"

#include "../../core/Application.h"

bool InputManager::current[GLFW_MOUSE_BUTTON_LAST] = { false };
bool InputManager::previous[GLFW_MOUSE_BUTTON_LAST] = { false };

bool InputManager::isKeyPressed(int keycode) {
    auto window = static_cast<GLFWwindow*>(Application::getInstance().getWindow().GetNativeWindow());
    return glfwGetKey(window, keycode) == GLFW_PRESS;
}

bool InputManager::isMouseButtonPressed(int button) {
    return current[button] && !previous[button];
}

bool InputManager::isMouseButtonReleased(int button) {
    return !current[button] && previous[button];
}

void InputManager::update() {
    for (int i=0; i < GLFW_MOUSE_BUTTON_LAST; ++i) {
        previous[i] = current[i];
        current[i] = glfwGetMouseButton(static_cast<GLFWwindow*>(Application::getInstance().getWindow().GetNativeWindow()), i) == GLFW_PRESS;
    }
}

glm::vec2 InputManager::getMousePosition() {
    auto window = static_cast<GLFWwindow*>(Application::getInstance().getWindow().GetNativeWindow());
    double xpos, ypos;
    glfwGetCursorPos(window, &xpos, &ypos);
    return {xpos, ypos};
}

glm::vec2 InputManager::getMousePositionNormalized() {
    glm::vec2 mousePos = getMousePosition();
    glm::vec2 windowSize = glm::vec2(Application::getInstance().getWindow().GetWidth(), Application::getInstance().getWindow().GetHeight());
    return mousePos / windowSize;
}

glm::vec2 InputManager::getMouseDelta() {
    static double lastX = 0, lastY = 0;
    double xpos, ypos;
    auto window = static_cast<GLFWwindow*>(Application::getInstance().getWindow().GetNativeWindow());
    glfwGetCursorPos(window, &xpos, &ypos);
    glm::vec2 delta(xpos - lastX, ypos - lastY);
    lastX = xpos;
    lastY = ypos;
    return delta;
}

bool InputManager::isMouseButtonDown(int button) {
    return current[button];
}

