#include "JC_Button.h" // https://github.com/JChristensen/JC_Button


const uint8_t greenLEDs[] = { 2, 3, 4, 5 };
const uint8_t redLED = 6;

Button buttons[] = { { 8 }, { 9 }, { 10 }, { 11 } };
Button buttonMode( 12 );


uint8_t randomLED()
{
  static uint8_t id = UINT8_MAX;
  const uint8_t old = id;
  
  if ( old != UINT8_MAX )
  {
    digitalWrite( greenLEDs[old], LOW );
  }

  while ( old == id )
  {
    id = random( 0, 4 );
  }

  digitalWrite( greenLEDs[id], HIGH );

  return id;
}


void setup()
{
  Serial.begin( 115200 );
  Serial.println( "Whack-a-LED started" );
  randomSeed( analogRead( A0 ) );

  for ( uint8_t i = 0; i < 4; ++i )
  {
    pinMode( greenLEDs[i], OUTPUT );
    buttons[i].begin();
  }

  pinMode( redLED, OUTPUT );
  buttonMode.begin();
}


void loop()
{
  const uint32_t now = millis();
  static uint32_t past = now;
  static uint32_t interval = 1000;
  static bool hit = true;
  static uint8_t id;

  if ( now - past >= interval )
  {
    past = now;
    hit = false;
    id = randomLED();
    digitalWrite( redLED, LOW );
  }

  if ( hit == false )
  {
    buttons[id].read();

    if ( buttons[id].wasPressed() )
    {
      hit = true;
      static uint16_t score = 0;
      Serial.print( "Hit! Score = " );
      Serial.println( ++score );
      digitalWrite( redLED, HIGH );

      // decrease interval every 5 hits..
      if ( score % 5 == 0 )
      {
        interval *= 0.9;
      }
    }
  }

  buttonMode.read();

  if ( buttonMode.wasPressed() )
  {
    Serial.println( "Modes are not implemented yet" );
  }
}