// Import the react-native-sound module
var Sound = require("react-native-sound");
// Enable playback in silence mode
Sound.setCategory("Playback");

const digitSoundList = {
  left: "ml_right.m4a",
  right: "ml_left.m4a",
  top: "ml_down.m4a",
  bottom: "ml_up.m4a",
  perfect: "ml_perfect.m4a",
};

const play = (audioName) => {
  try {
    if (audioName == null || audioName == undefined) {
      console.log("*** DSound audioName not provided");
      return;
    }
    // Load the sound file 'digitSound.mp3' from the app bundle
    // See notes below about preloading sounds within initialization code below.
    var digitSound = new Sound(audioName, Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.log("*** DSound failed to load the sound", error);
        return;
      }
      // loaded successfully
      console.log(
        "*** DSound duration in seconds: " +
          digitSound.getDuration() +
          "number of channels: " +
          digitSound.getNumberOfChannels()
      );
      // Play the sound with an onEnd callback
      digitSound.play((success) => {
        if (success) {
          // Release the audio player resource
          digitSound.release();
          console.log("*** DSound successfully finished playing");
        } else {
          console.log(
            "*** DSound playback failed due to audio decoding errors"
          );
        }
      });
    });
    digitSound.setVolume(1.0);
    // Loop indefinitely until stop() is called
    digitSound.setNumberOfLoops(0);

    const stop = () => {
      digitSound.stop(() => {
        // Note: If you want to play a sound after stopping and rewinding it,
        // it is important to call play() in a callback.
        // digitSound.play();

        // Release the audio player resource
        digitSound.release();
      });
    };
    return stop;
  } catch (error) {
    console.log(error);
  }
  return null;
};

export { play, digitSoundList };
