#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "logo.h"

/* SSD1306 OLED 128x64 */
#define SSD1306_DEFAULT_ADDR      0x3C
#define OLED_WIDTH                128
#define OLED_HEIGHT               64
#define OLED_RESET                -1  // Reset pin # (or -1 if sharing Arduino reset pin)
#define OLED_DOWN                 0
#define OLED_LEFT                 1
#define OLED_UP                   2
#define OLED_RIGHT                3

/* Joystick */
#define JOY_SEL_PIN               2
#define JOY_X_PIN                 A2
#define JOY_Y_PIN                 A3
#define JOY_RESOLUTION            1023  //10bit

Adafruit_SSD1306          _oled(OLED_WIDTH, OLED_HEIGHT, &Wire, OLED_RESET);
static uint8_t            _displayAddr = SSD1306_DEFAULT_ADDR;
static uint8_t            _screenOn = 1;
static uint8_t            _rotation = OLED_DOWN;

static void LocalDrawLogo(uint8_t rotation);

void setup() {
  pinMode(JOY_SEL_PIN, INPUT_PULLUP);
  pinMode(JOY_X_PIN, INPUT);
  pinMode(JOY_Y_PIN, INPUT);

  if(_oled.begin(SSD1306_SWITCHCAPVCC, _displayAddr)) {
    _oled.setTextSize(1);
    _oled.setTextColor(SSD1306_WHITE);
    LocalDrawLogo(_rotation);
  }
}

void loop() {
  bool isUpdate = true;

  uint8_t sel = digitalRead(JOY_SEL_PIN);
  if (_screenOn != sel) {
    _screenOn = sel;
    if (!_screenOn) {
      _oled.clearDisplay();
      _oled.display();
    } else {
      LocalDrawLogo(_rotation);
    }
  }

  if (_screenOn) {
    uint16_t joy_percent_x = map(analogRead(JOY_X_PIN), 0, JOY_RESOLUTION, 0, 100);
    uint16_t joy_percent_y = map(analogRead(JOY_Y_PIN), 0, JOY_RESOLUTION, 0, 100);

    if (joy_percent_x >= 80) {
      _rotation = OLED_LEFT;
    } else if (joy_percent_x <= 20) {
      _rotation = OLED_RIGHT;
    } else if (joy_percent_y >= 80) {
      _rotation = OLED_UP;
    } else if (joy_percent_y <= 20) {
      _rotation = OLED_DOWN;
    } else {
      isUpdate = false;
    }

    if (isUpdate) {
      LocalDrawLogo(_rotation);
    }
  }
}

void LocalDrawLogo(uint8_t rotation)
{
  uint16_t x = 0, y = 0;
  switch (rotation) {
    case OLED_DOWN:
    case OLED_UP:
      x = 32; y = 0;
    break;

    case OLED_LEFT:
    case OLED_RIGHT:
      x = 0; y = 32;
      break;
  }

  _oled.setRotation(rotation);
  _oled.clearDisplay();
  _oled.drawBitmap(x, y, humalogo, LOGO_WIDTH, LOGO_HEIGHT, SSD1306_WHITE);
  _oled.display();
}