#include <string.h>
#include <SDL.h>
#include "Kempston.h"

static Uint8 _kempston_state = 0x00;
static Uint8 _bad_input = 0x00;

struct optToKempstonFlag {
	const char* commandLineOption;
	Uint8 kempstonFlag;
};

#define NUM_SUPPORTED_COMMAND_LINE_OPTIONS 5
static struct optToKempstonFlag _commandLineOptionsToKempstonFlag[NUM_SUPPORTED_COMMAND_LINE_OPTIONS] = {
	{"kemp_up", KEMPSTON_UP},
	{"kemp_down", KEMPSTON_DOWN},
	{"kemp_left", KEMPSTON_LEFT},
	{"kemp_right", KEMPSTON_RIGHT},
	{"kemp_fire", KEMPSTON_FIRE},
};

/// <summary>
/// Resolves Kempston flag from a command line option
/// </summary>
/// <param name="key">command line option</param>
/// <returns>NULL when not found</returns>
Uint8* _getKempstonFlagForCommandLineOption(const char* key) {
	for (int i = 0; i < NUM_SUPPORTED_COMMAND_LINE_OPTIONS; i++) {
		if (!strcmp(_commandLineOptionsToKempstonFlag[i].commandLineOption, key)) {
			return &_commandLineOptionsToKempstonFlag[i].kempstonFlag;
		}
	}

	return NULL;
}

Uint8 _kempston_map_button(SDL_Keysym key) {
	switch (key.sym) {
	case SDLK_UP: return KEMPSTON_UP;
	case SDLK_DOWN: return KEMPSTON_DOWN;
	case SDLK_LEFT: return KEMPSTON_LEFT;
	case SDLK_RIGHT: return KEMPSTON_RIGHT;
	case SDLK_LCTRL: return KEMPSTON_FIRE;

	default: return 0;
	}
}

void kempston_start() {

}

void kempston_destroy() {

}

Uint8 kempston_read8(Uint16 address) {
	switch (address & 0xFF) {
	case 0x1F: return _kempston_state;
	default: return _bad_input;
	}
}

Uint8 kempston_is_supported_address(Uint16 address) {
	switch (address & 0xFF) {
	case 0x1F:
		return 1;
	default: return 0;
	}
}

void kempston_buttonup(Uint8 kempstonButton)
{
	_kempston_state &= ~kempstonButton;
}

void kempston_buttondown(Uint8 kempstonButton)
{
	_kempston_state |= kempstonButton;
}

Uint8 kempston_try_resolve_button_flag_from_override(const char* override, Uint8* kempstonFlagOUT)
{
	Uint8* temp;
	temp = _getKempstonFlagForCommandLineOption(override);
	if (temp == NULL) {
		return 0;
	}

	*kempstonFlagOUT = *temp;
	return 1;
}

void kempston_keyup(SDL_Keysym key) {
	Uint8 button = _kempston_map_button(key);
	kempston_buttonup(button);
}

void kempston_keydown(SDL_Keysym key) {
	Uint8 button = _kempston_map_button(key);
	kempston_buttondown(button);
}

