#include "input.h"
#include <SDL2/SDL_events.h>
#include <SDL2/SDL_log.h>
#include <SDL2/SDL_scancode.h>

namespace rogue {
InputHandler::InputHandler() {
	Input::add_handler(this);
}

InputHandler::~InputHandler() {
	Input::remove_handler(this);
}

KeyEventHandler::KeyEventHandler(std::set<SDL_Scancode> codes, Listener listener, bool allow_repeat)
: scancodes{codes}
, listener{listener}
, allow_repeat{allow_repeat}
{}

void KeyEventHandler::process_event(SDL_Event event) {
	// check if this event is an event related to keys
	if((event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)
	// check if it is an allowed event (either non-repeated or repetition is allowed)
	&& (event.key.repeat == 0 || this->allow_repeat)
	// check if it is one of our keys
	&& this->scancodes.contains(event.key.keysym.scancode)) {
		// trigger event, notifying it if the key was pressed or released
		this->listener(event.type == SDL_KEYDOWN);
	}
}

void Input::add_handler(InputHandler *handler) {
	Input::handlers.insert(handler);
}

void Input::remove_handler(InputHandler *handler) {
	Input::handlers.erase(handler);
}

void Input::process_event(SDL_Event event) {
	for(InputHandler *handler : Input::handlers) {
		handler->process_event(event);
	}
}

std::set<InputHandler*> Input::handlers{};
}
