#include "input.h"

Input::Input()
{
    SDL_Init(SDL_INIT_JOYSTICK);
    exit = false;
}

void Input::update()
{
    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_CONTROLLERBUTTONDOWN:
            controllers[event.cbutton.which].buttons[event.cbutton.button] = true;
            break;
        case SDL_CONTROLLERBUTTONUP:
            controllers[event.cbutton.which].buttons[event.cbutton.button] = false;
            break;
        case SDL_MOUSEBUTTONDOWN:
            mouse.buttons[event.button.button] = true;
            break;
        case SDL_MOUSEBUTTONUP:
            mouse.buttons[event.button.button] = false;
            break;
        case SDL_KEYDOWN:
            activeKeys[event.key.keysym.sym] = true;    
            break;
        case SDL_KEYUP:
            activeKeys.erase(event.key.keysym.sym);
            break;
        case SDL_CONTROLLERDEVICEADDED:
            controllers[SDL_NumJoysticks() - 1] = {
                SDL_GameControllerOpen(SDL_NumJoysticks() - 1),
                SDL_GameControllerName(SDL_GameControllerOpen(SDL_NumJoysticks() - 1))
            };
            printf("Controller added: %s\n", controllers[SDL_NumJoysticks() - 1].name.c_str());
            break;
        case SDL_QUIT:
            exit = true;
            break;
        }
        for (auto& controller : controllers)
        {
            controller.second.leftStickX = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_LEFTX);
            controller.second.leftStickY = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_LEFTY);
            controller.second.rightStickX = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_RIGHTX);
            controller.second.rightStickY = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_RIGHTY);
            controller.second.leftTrigger = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
            controller.second.rightTrigger = SDL_GameControllerGetAxis(controller.second.controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
        }
        SDL_GetMouseState(&mouse.x, &mouse.y);
        mouse.wheel = event.wheel.y;
    }
}

bool Input::keysPressed(std::vector<SDL_Keycode> keys)
{
    for (auto key : keys)
    {
        if (activeKeys[key])
        {
            return true;
        }
    }
    return false;
}

bool Input::controllerPressed(std::vector<Uint8> buttons, int controller)
{
    for (auto button : buttons)
    {
        if (controllers[controller].buttons[button])
        {
            return true;
        }
    }
    return false;
}