#include "plugin.h"
#include "lib/playergfx.h"
#include "lib/pluginlib_actions.h"

#ifdef HAVE_LCD_BITMAP
#include "pluginbitmaps/bkp2017_background.h"
#endif

static const int BACKGROUND_X = 0;
static const int BACKGROUND_Y = 0;

static const unsigned BACKGROUND = LCD_RGBPACK(0xfa, 0xf8, 0xef);

char flag[] = {71, 76, 73, 124, 110, 117, 88, 100, 102, 107, 88, 102, 109, 116, 41, 88, 105, 109, 102, 126, 88, 106, 114, 116, 110, 100, 122, 0};

/* this set the context to use with PLA */
static const struct button_mapping *plugin_contexts[] = { pla_main_ctx,
#ifdef HAVE_REMOTE_LCD
	pla_remote_ctx,
#endif
};

const int lab[8][8] = {
	{0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 1, 2, 0},
	{0, 1, 1, 1, 0, 1, 0, 0},
	{0, 1, 0, 1, 0, 1, 1, 0},
	{0, 1, 0, 1, 0, 0, 1, 0},
	{0, 1, 0, 1, 1, 0, 1, 0},
	{0, 1, 0, 0, 1, 1, 1, 0},
	{0, 0, 0, 0, 0, 0, 0, 0},
};

enum plugin_status plugin_start(const void* parameter) {
	int button;
	int x = 6;
	int y = 1;
	int changed = 0;
	(void)parameter;

	rb->lcd_set_backdrop(NULL);
	rb->lcd_clear_display();

	rb->lcd_bitmap(bkp2017_background, 0, 0, LCD_WIDTH, LCD_HEIGHT);
	rb->lcd_update();

	while (1) {
		button = pluginlib_getaction(TIMEOUT_NOBLOCK, plugin_contexts, ARRAYLEN(plugin_contexts));

		switch (button) {
			case PLA_EXIT:
				return PLUGIN_OK;
			case PLA_DOWN:
				if (lab[x-1][y] == 0) {
					x = 6;
					y = 1;
				} else {
					x -= 1;
				}
				break;
			case PLA_RIGHT:
				if (lab[x+1][y] == 0) {
					x = 6;
					y = 1;
				} else {
					x += 1;
				}
				break;
			case PLA_UP:
				if (lab[x][y-1] == 0) {
					x = 6;
					y = 1;
				} else {
					y -= 1;
				}
				break;
			case PLA_LEFT:
				if (lab[x][y+1] == 0) {
					x = 6;
					y = 1;
				} else {
					y += 1;
				}
				break;
			default:
				break;
		}
		if (lab[x][y] == 2) {
			if (changed == 0) {
				for(unsigned int i=0; i < sizeof(flag); i++) {
					flag[i] = (flag[i] ^ y) + x;
				}
			}
			changed = 1;
			flag[sizeof(flag)-1] = '\0';
			rb->splashf(HZ*2, "%s", flag);
			rb->lcd_update();
		}

		rb->yield();
	}

	return PLUGIN_OK;
}
