#include <input_handler.hpp>
#include <toolbox.hpp>
#include <SDL.h>
#include <iostream>

void InputHandler::update(Toolbox& tb) {
	bool contains_touch_events = false;
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		switch (event.type) {
		case SDL_FINGERDOWN:
		case SDL_FINGERUP:
		case SDL_FINGERMOTION:
			contains_touch_events = true;
			//Uncomment on a touchscreen
			//tb.events.push_back(tb.pevFactory(event));
		case SDL_QUIT:
		case SDL_MOUSEBUTTONDOWN:
		case SDL_MOUSEBUTTONUP:
		case SDL_MOUSEMOTION:
			/*TODO: the PeventFactory should probably be owned by InputHandler*/
			//Comment out on a touchscreen
			tb.events.push_back(tb.pevFactory(event));
			break;
		default:
			break;
		}
	}

	/*Update touch state*/
	if (tb.touch_device == 0) {
		tb.touch_device = SDL_GetTouchDevice(0);
	}
	if (tb.touch_device != 0) {
		tb.current_touchIDs.clear();
		for (size_t i = 0; i < SDL_GetNumTouchFingers(tb.touch_device); ++i) {
			tb.current_touchIDs.push_back(SDL_GetTouchFinger(tb.touch_device, i)->id);
		}
	}

	/*Sanitize events: if we have a touch event, we don't allow mouse events*/
	/*Not doint this for now, might break GUI
	if (contains_touch_events) {
		tb.events.remove_if(
			[](const Pevent& pev) {
				return pev.event.type == SDL_MOUSEBUTTONDOWN || pev.event.type == SDL_MOUSEBUTTONUP || pev.event.type == SDL_MOUSEMOTION;
			});
	}*/
}