#include "menu.h"
#include "debounce.h"
#include "actuation.h"
#include "rotary_encoder.h"

#define RE_CLK 13
#define RE_DT 12
#define RE_SW 9

RotaryEncoder rotary(RE_DT, RE_CLK);
Debounce btn;

void setup() {
  Serial.begin(9600);

  if(!displayBegin()) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  pinMode(RE_SW, INPUT_PULLUP);
  setupActuation();
}

bool processing = false;

void loop() {
	processing
    ? process()
	  : btn.debounce(&click, 50);

  rotary.decode(&cw, &ccw);
}

bool clicked = false;
unsigned int length;
unsigned int qty;

void click() {
	if (digitalRead(RE_SW) == LOW && !clicked) {
    clicked = true;

		if (cursor < parameter_length) {
      selected = !selected;
    } else {
      processing = !processing;
      length = values[0];
      qty = values[1];
    }

    displayUpdate();
  } else if (digitalRead(RE_SW) == HIGH && clicked) {
    clicked = false;
  }
}

void cw() {
  if (!selected && cursor == parameter_length)
		return;

	if (selected) {
    if (cursor == 1 && values[1] < 100) {
      values[1]++;
    } else if (cursor == 0 && values[0] < 250) {
      values[0]++;
    }
  } else {
    cursor++;
  }

  displayUpdate();
}

void ccw() {
  if (!selected && cursor == 0)
  // if (!selected && cursor == 1)
		return;

	if (selected) {
    if (cursor == 1 && values[1] > 1) {
      values[1]--;
    } else if (cursor == 0 && values[0] > 10) {
      values[0]--;
    }
  } else {
    cursor--;
  }

  displayUpdate();
}
A4988