#include "gameplay/input.h"
#include "utility/command.h"

#include <SDL_timer.h>

void InputHandler::handleInput() {
  // If our input handler is not attached to an actor we return.
  // This will be due for change given we will need to handle input during menus
  if (!actor)
    return;
  Uint32 currentTime = SDL_GetTicks();
  // check for bound keys that were pressed,
  // next check if the hasn't been executed within the amount specified in delay
  // if not execute the command and set lastExecution to currentTime
  for (auto &[key, command] : keyCommands) {
    if (keys[key] == true) {
      if (currentTime - command.lastExecution >= command.delay) {
        commandQueue.push_back(command.cmd.get());
        command.lastExecution = currentTime;
      }
    }
  }
  // Same with the mouse, for this context we'll be checking for motion events
  // and for click events
  for (auto &[button, command] : mouseCommands) {
    if (mouseButtons[button] == true) {
      if (currentTime - command.lastExecution >= command.delay) {
        mouseQueue.push_back(command.cmd.get());
        command.lastExecution = currentTime;
      }
    }
  }
  if (mouseMotionCommand)
    mouseMotionCommand->execute(*actor, mouse_state);
  if (mouseScrollCommand)
    mouseScrollCommand->execute(*actor, mouse_state);
  mouse_state.scroll =
      0.0f; // clear mouse scroll since we have handled the event.
}

// Executes every captured command during the frame
void InputHandler::executeCommands() {
  for (auto &command : commandQueue) {
    command->execute(*actor);
  }
  for (auto &mouse : mouseQueue) {
    mouse->execute(*actor, mouse_state);
  }
  commandQueue.clear();
  mouseQueue.clear();
}

InputHandler::~InputHandler() {}
