#include <game/input.hpp>

namespace Game {
    const bool* Input::mCurrentKeyStates = nullptr;
    const bool* Input::mPreviousKeyStates = nullptr;
    int Input::mNumKeys = 0;
    SDL_MouseButtonFlags Input::mCurrentMouseButtonStates = 0;
    SDL_MouseButtonFlags Input::mPreviousMouseButtonStates = 0;
    float Input::mMouseX = 0.0f;
    float Input::mMouseY = 0.0f;

    void Input::update() {
        mPreviousKeyStates = mCurrentKeyStates;
        mCurrentKeyStates = SDL_GetKeyboardState(&mNumKeys);

        mPreviousMouseButtonStates = mCurrentMouseButtonStates;
        mCurrentMouseButtonStates = SDL_GetMouseState(&mMouseX, &mMouseY);
    }

    bool Input::isKeyPressed(SDL_Scancode key) {
        if (key < 0 || key >= mNumKeys) return false;
        return mCurrentKeyStates[key];
    }

    bool Input::isKeyJustPressed(SDL_Scancode key) {
        if (key < 0 || key >= mNumKeys) return false;
        return mCurrentKeyStates[key] && (!mPreviousKeyStates || !mPreviousKeyStates[key]);
    }

    bool Input::isKeyJustReleased(SDL_Scancode key) {
        if (key < 0 || key >= mNumKeys) return false;
        return (!mCurrentKeyStates[key]) && mPreviousKeyStates && mPreviousKeyStates[key];
    }

    bool Input::isMouseButtonPressed(Uint8 button) {
        return (mCurrentMouseButtonStates & SDL_BUTTON_MASK(button)) != 0;
    }

    bool Input::isMouseButtonJustPressed(Uint8 button) {
        return (mCurrentMouseButtonStates & SDL_BUTTON_MASK(button)) != 0 && (mPreviousMouseButtonStates & SDL_BUTTON_MASK(button)) == 0;
    }

    bool Input::isMouseButtonJustReleased(Uint8 button) {
        return (mCurrentMouseButtonStates & SDL_BUTTON_MASK(button)) == 0 && (mPreviousMouseButtonStates & SDL_BUTTON_MASK(button)) != 0;
    }

    float Input::getMouseX() {
        return mMouseX;
    }

    float Input::getMouseY() {
        return mMouseY;
    }
}