#include "Arduino.h"

// TODO : ce serait l'occasion de jouer avec les submodules pour mettre
//        fastled dans le dossier lib
#include <FastLED.h>

#include "ledmask.h"

/** BUTTON **/
void buttonCheckState() {
  if (digitalRead(BUTTON_EYES_PIN) == HIGH) {
    Serial.println("E: HIGH");
    ledPartyState = false;
    if (ledEyesState) {
      ledEyesState = true;
      // TODO : lancer l' "ouverture" des yeux
    } else {
      ledEyesState = false;
      // TODO : lancer le "déclin" des yeux
    }
  }

  if (digitalRead(BUTTON_PARTY_PIN) == HIGH) {
    Serial.println("P: HIGH");
    ledEyesState  = false;
    if (ledPartyState) {
      ledPartyState = true;
    } else {
      ledPartyState = false;
    }
  }
}

/** LEDS **/
/**
* Coupe tout le strip de led.
*/
void ledBlackAll()
{
  FastLED.clear();
  FastLED.show();
}

/** FIRE2012 **/
void Fire2012()
{
  // Array of temperature readings at each simulation cell
  static byte heat[LED_NUM];

  // Step 1.  Cool down every cell a little
  for (int i = 0; i < LED_NUM; i++) {
    heat[i] = qsub8(heat[i],  random8(0, ((COOLING * 10) / LED_NUM) + 2));
  }

  // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  for (int k = LED_NUM - 1; k >= 2; k--) {
    heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  }

  // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  if (random8() < SPARKING ) {
    int y   = random8(7);
    heat[y] = qadd8(heat[y], random8(160,255));
  }

  // Step 4.  Map from heat cells to LED colors
  for (int j = 0; j < LED_NUM; j++) {
    CRGB color = HeatColor(heat[j]);
    leds[(LED_NUM - 1) - j] = color;
  }
}


void setup() {
  Serial.begin(SERIAL_SPEED);
  Serial.println("\nresetting");

  /** BOUTON EYES **/
  // powering button
  pinMode(BUTTON_EYES_POWERPIN, OUTPUT);
  digitalWrite(BUTTON_EYES_POWERPIN, HIGH);
  // initialize the pushbutton pin as an input:
  pinMode(BUTTON_EYES_PIN, INPUT);

  /** BOUTON PARTY **/
  // powering button
  pinMode(BUTTON_PARTY_POWERPIN, OUTPUT);
  digitalWrite(BUTTON_PARTY_POWERPIN, HIGH);
  // initialize the pushbutton pin as an input:
  pinMode(BUTTON_PARTY_PIN, INPUT);
  delay(100);

  /** LEDS **/
  LEDS.addLeds<LED_CHIPSET,LED_PIN, LED_COLOR_ORDER>(leds, LED_NUM).setCorrection(TypicalSMD5050);
  FastLED.setBrightness(LED_BRIGHTNESS);
}

void loop() {
  /** BOUTON **/
  EVERY_N_MILLISECONDS(300) {
    buttonCheckState();
  }

  /** LEDS **/
  if (ledEyesState) {
    fill_solid(leds, LED_NUM, CRGB::Red);
    FastLED.delay(1000 / LED_FPS);
  } else if (ledPartyState) {
    // Add entropy to random number generator; we use a lot of it.
    random16_add_entropy(random());
    Fire2012();
    FastLED.delay(1000 / LED_FPS);
  } else {
    ledBlackAll();
  }
}
