// Blynk constants
#define BLYNK_TEMPLATE_ID "TMPL60QlFt1kY"
#define BLYNK_TEMPLATE_NAME "Bedroom Device"
#define BLYNK_AUTH_TOKEN "nKBCaSuiSRiqX3O9dJSCcP8zVzLiNJgA"
#define BLYNK_PRINT SerialUSB

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <Adafruit_CircuitPlayground.h>

// Wifi setup stuff
char ssid[] = "HPNA3-163";
char pass[] = "0051755081";
#define EspSerial Serial1
#define ESP8266_BAUD 115200
ESP8266 wifi(&EspSerial);

// Timer for the sound level
BlynkTimer timer;

// This tells us whether the sound should be playing or not
int isLightOff = 0;

// Notes for the nightmarish song tune
#define NOTE_E5  (659)
#define NOTE_D5  (587)
#define NOTE_FS4 (370)
#define NOTE_GS4 (415)
#define NOTE_CS5 (554)
#define NOTE_B4  (494)
#define NOTE_D4  (294)
#define NOTE_E4  (330)
#define NOTE_A4  (440)
#define NOTE_CS4 (277)

// All the notes in the tune, their tempo and beat, and the notes amount
float tune_notes[] = {NOTE_E5, NOTE_D5, NOTE_FS4, NOTE_GS4, NOTE_CS5, NOTE_B4, NOTE_D4, NOTE_E4, NOTE_B4, NOTE_A4, NOTE_CS4, NOTE_E4, NOTE_A4};
int tune_beats[] = {4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2};
int tempo = 40;
const int notes_length = sizeof(tune_notes) / sizeof(tune_notes[0]);

// This tells us whether the sound should be playing or not
#define LIGHT_THRESHOLD (30)

int isFirstPlay = 1;

void setup()
{
    // Debug console
    SerialUSB.begin(115200);
    CircuitPlayground.begin();

    // Set ESP8266 baud rate
    EspSerial.begin(ESP8266_BAUD);
    delay(10);

    Blynk.begin(BLYNK_AUTH_TOKEN, wifi, ssid, pass);
    timer.setInterval(1000L, sendLightTurnedOff); // Send the light level once every 1s
}

void sendLightTurnedOff() {
    int lightLevel = CircuitPlayground.lightSensor();

    if (lightLevel < LIGHT_THRESHOLD && !isLightOff) {
        Blynk.virtualWrite(V0, 1);
        isLightOff = 1;
    } else if (lightLevel >= LIGHT_THRESHOLD && isLightOff) {
        Blynk.virtualWrite(V0, 0);
        isLightOff = 0;
    }
}

void loop() {
    Blynk.run();
    timer.run();
    if (isLightOff) {
        if (isFirstPlay) {
            // Add a delay so the other device can sync up to our nightmarish tune
            delay(200);
            isFirstPlay = 0;
        }

        // Play the tune
        for (int i = 0; i < notes_length; i++) {
            CircuitPlayground.playTone(tune_notes[i], tune_beats[i] * tempo);
        }
    } else {
        isFirstPlay = 1;
    }
}
