#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ELECHOUSE_CC1101_SRC_DRV.h>

#define OLED_RESET     -1
#define SCREEN_WIDTH   128
#define SCREEN_HEIGHT  64
#define MENU_ITEMS     3

#define BUTTON_UP_PIN     12
#define BUTTON_DOWN_PIN   13
#define BUTTON_RETURN_PIN 14
#define BUTTON_SELECT_PIN 15

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char *menu[MENU_ITEMS] = {"Sketch 1", "Sketch 2", "Sketch 3"};
int selected = 0;

void setup() {
  pinMode(BUTTON_UP_PIN, INPUT_PULLUP);
  pinMode(BUTTON_DOWN_PIN, INPUT_PULLUP);
  pinMode(BUTTON_RETURN_PIN, INPUT_PULLUP);
  pinMode(BUTTON_SELECT_PIN, INPUT_PULLUP);

  Wire.begin();

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("Menu");
  display.display();
}

void loop() {
  if (digitalRead(BUTTON_UP_PIN) == LOW) {
    selected = (selected - 1 + MENU_ITEMS) % MENU_ITEMS;
    updateMenu();
  }
  if (digitalRead(BUTTON_DOWN_PIN) == LOW) {
    selected = (selected + 1) % MENU_ITEMS;
    updateMenu();
  }
  if (digitalRead(BUTTON_RETURN_PIN) == LOW) {
    returnToMenu();
  }
  if (digitalRead(BUTTON_SELECT_PIN) == LOW) {
    executeSelectedSketch();
  }
}

void updateMenu() {
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println("Menu");
  for (int i = 0; i < MENU_ITEMS; i++) {
    if (i == selected) {
      display.print(">");
    }
    else {
      display.print(" ");
    }
    display.println(menu[i]);
  }
  display.display();
}

void returnToMenu() {
  selected = 0;
  updateMenu();
}

void executeSelectedSketch() {
  switch (selected) {
    case 0:
      // execute Sketch 1
      break;
    case 1:
      // execute Sketch 2
      break;
    case 2:
      // execute Sketch 3
      break;
    default:
      break;
  }
}