#include "SegmentDisplay.h"

#define ASCIIUppercaseA 65
#define ASCIIUppercaseZ 90

SegmentDisplay* display;

char* text = new char[7];


void setup()
{
  pinMode(2, INPUT_PULLUP);
  pinMode(A3, INPUT);

  display = new SegmentDisplay();
  //display->setClockSpeed(4000000UL);
  display->setClockPin(12);
  display->setDataPin(11);
  display->setLatchPin(10);
  display->setDigits(6);
  display->begin();

  text[0] = '\0';
  text[1] = '\0';
  text[2] = '\0';
  text[3] = '\0';
  text[4] = '\0';
  text[5] = '\0';
  text[6] = '\0';
}

unsigned long currentTime;
unsigned long lastCounterTime = 0;
uint32_t counter = 0;
uint32_t delayValue;

bool showChars = true;
byte character = ASCIIUppercaseA - 1;

int buttonValue;
bool buttonDown = false;
unsigned long lastButtonChange = 0;



void loop()
{
  currentTime = millis();

  buttonValue = digitalRead(2);
  if (buttonValue == LOW)
  {
    if (!buttonDown && (currentTime - lastButtonChange) > 50)
    {
      buttonDown = true;
      showChars = !showChars;
      lastButtonChange = currentTime;
    }
  }
  else
  {
    if (buttonDown && (currentTime - lastButtonChange) > 50)
    {
      buttonDown = false;
      lastButtonChange = currentTime;
    }
  }

  if (showChars)
  {
    if (lastCounterTime == 0 || currentTime - lastCounterTime > 250UL)
    {
      character++;
      if (character > ASCIIUppercaseZ)
        character = ASCIIUppercaseA;

      lastCounterTime = currentTime;

      delayValue = ((uint32_t)analogRead(A3) * 100);
      display->setDigitDelayMicroseconds(delayValue);
    }

    for (byte c = 0; c < 6; c++)
    {
      if (character + c > ASCIIUppercaseZ)
        text[c] = ' ';
      else
        text[c] = character + c;
    }

    display->writeTextLeft(text);
  }
  else
  {
    if (currentTime - lastCounterTime > 100UL)
    {
      counter++;
      if (counter > 999999)
        counter = 0;

      lastCounterTime = currentTime;

      delayValue = ((uint32_t)analogRead(A3) * 100);
      display->setDigitDelayMicroseconds(delayValue);
    }

    display->writeNumber(counter);
  }
}
