#include <WebUSB.h>

/**
   Creating an instance of WebUSBSerial will add an additional USB interface to
   the device that is marked as vendor-specific (rather than USB CDC-ACM) and
   is therefore accessible to the browser.

   The URL here provides a hint to the browser about what page the user should
   navigate to to interact with the device.
*/
WebUSB WebUSBSerial(1 /* https:// */, "apollo.antoine-rcbs.ovh/activity_1");
DFMiniMp3<HardwareSerial, Mp3Notify> mp3(Serial1);

#define Serial WebUSBSerial

#define RING_PIN 2

String currentCommand = "";





void setup() {
  while (!Serial) {
    ;
  }
  Serial.begin(9600);
  Serial.println("Arduino connected and answering");
  delay(1000);
  Serial.flush();
}

void loop() {
  if (Serial) {
    while (Serial.available() > 0) {
      char c = '0';
      while (c != ';') {
        c = Serial.read();
        currentCommand += c;
        delay(1);
      }
      runCommand(currentCommand);
      currentCommand = "";
    }
    Serial.flush();
  }
}


void runCommand(String command) {
  //Décomposition de la commande en ID + arguments
  int curIndex = command.indexOf('_');
  String id = command.substring(0, curIndex);
  Serial.print(id);
  String args[5] = {"0", "0", "0", "0", "0"}; //Max 5 args
  for (int i = 0; i < 5; i++) {
    int nextIndex = command.indexOf('_', curIndex + 1);
    args[i] = command.substring(curIndex + 1, nextIndex);
    Serial.print(args[i]);
    curIndex = nextIndex;
    if (args[i].endsWith(";")) {
      args[i].remove(args[i].indexOf(';'));
      break;
    }
  }


  //Lancement des diverses commandes
  if (id == "IO") {
    turnIO(args[0].toInt(), args[1].toInt());
  } else if (id == "DELAY") {
    waitForUnlock(args[0].toInt());
  } 
}

/* FONCTIONS METIER */

void turnIO(int pin, boolean val) {
  digitalWrite(pin, val);
}

void waitForUnlock(int delayMs) {
  delay(delayMs);
  Serial.println("UNLOCK;");
}
