#include <Arduino.h>
#include "SoundPlayer.h"

/**
 * Store the array of pin numbers that the sound card is connected to.
 *
 * int soundPins[]: An array of pin numbers that the sound card is connected to.
 * int soundPinCount: Array size
 */
SoundPlayer::SoundPlayer(int soundPins[], int soundPinCount) {
  this->soundPins = soundPins;
  this->soundPinCount = soundPinCount;

  //If a random mode existed
  //make this more random between sketch executions
  //randomSeed(analogRead(0));
}

/**
 * Initialize the output pins that will trigger the sound card.
 */
void SoundPlayer::Initialize() {
  //set the sound pins to output
  for (int i=0; i<soundPinCount;i++) {
    pinMode(soundPins[i], OUTPUT);  //low = active
    digitalWrite(soundPins[i], HIGH);
  }
}

/**
 * Trigger the next sound to play.
 */
void SoundPlayer::PlayNextSound() {
  PlaySound(soundPins[clipToPlay]);

  //Advance sound clips
  clipToPlay++;

  //If we have advanced past the last sound clip, return to clip 0.
  if (clipToPlay >= soundPinCount) {
    clipToPlay = 0;
  }
}

/**
 * Play a sound once.
 *
 * The sound chip is set to play a sound all the way through once started
 * (unless another sound is triggered).
 * So turn the sound on, have a brief delay, then turn it off.
 * This method delays for 100ms.
 *
 * int soundPin: The Arduino pin to output the signal on.
 *
 * LOW = play sound
 */
void SoundPlayer::PlaySound(int soundPin)
{
  if (debug) {
    Serial.println("PlaySound(): " + String(soundPin) + " Clip: " + String(this->clipToPlay));
  }

  digitalWrite(soundPin, LOW);
  delay(this->triggerDelay);
  digitalWrite(soundPin, HIGH);
}