// 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 digitPreAudios = {
  bonnet: "aa_01_open_bonnet.m4a",
  start_car: "bb_02_start_car.m4a",
  chassis: "cc_03_find_chassis_number.m4a",
  ready: "dd_04_ready.m4a",
};

const chp = "a_01_chp.m4a";
const engine_bay = "b_02_engine_bay.m4a";
const close_bonnet = "c_03_close_bonnet.m4a";
const fs = "d_04_fs.m4a";
const dbd = "n_14_dbd.m4a";
const inside_wnd = "m_13_inside_wnd.m4a";

const digitAudios_nonGdd = [
  chp,
  engine_bay,
  close_bonnet,
  fs,
  "e_05_flc.m4a",
  "f_06_ls.m4a",
  "g_07_blc.m4a",
  "h_08_bs.m4a",
  "i_09_brc.m4a",
  "j_10_rs.m4a",
  "k_11_frc.m4a",
  "l_12_wnd.m4a",
  inside_wnd,
  dbd,
];

const digitAudios_Gdd = [
  fs,
  "f_06_ls.m4a",
  "h_08_bs.m4a",
  "j_10_rs.m4a",
  fs,
  inside_wnd,
  dbd,
];

const extraTime = {
  [chp]: 0,
  [engine_bay]: 0,
  // [fs]: 20 * 1000,
  // [dbd]: 3 * 1000,
  // [inside_wnd]: 3 * 1000,
  // remaining all should get 3 sec
};

const getWithExtraTime = (audioName) => {
  var eTime = 3 * 1000; // default extra time for each pose
  const extra = extraTime[audioName];
  if (extra) {
    eTime = extra;
  }
  return eTime;
};

const prepareNAdd = (list, audioName, nextCallback, isGdd) => {
  const snd = new Sound(audioName, Sound.MAIN_BUNDLE, (error) => {
    if (error) {
      console.log("*** DSound failed to load the sound: " + audioName, error);
      list.push({ track: null, duration: 0 });
      if (nextCallback) {
        nextCallback(0);
      }
      return;
    }
    console.log("*** DSound prepareNAdd: " + audioName);

    var newDuration;
    if (isGdd) {
      newDuration = Math.floor(snd.getDuration() * 1000 * 2); // double the duration
    } else {
      newDuration = Math.floor(
        snd.getDuration() * 1000 + getWithExtraTime(audioName)
      ); // increase by 3 sec
    }
    list.push({ track: snd, duration: newDuration }); // convert sec to millisec
    if (nextCallback) {
      nextCallback(newDuration); // convert sec to millisec
    }
  });
};

const prepareAudioList = (digitAudios, isGdd) => {
  return new Promise((resolve, reject) => {
    const list = [];
    var index = 0;
    var duration = 0; // sec
    const callback = (nextDuration) => {
      duration = duration + nextDuration;
      index = index + 1;
      if (index < digitAudios.length) {
        prepareNAdd(list, digitAudios[index], callback, isGdd);
      } else {
        // All sounds loaded
        resolve({ audioList: list, totalDuration: duration }); // This will be returned
      }
    };
    prepareNAdd(list, digitAudios[index], callback, isGdd);
  });
};

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: " +
          Math.floor(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 " + audioName);
        } else {
          console.log(
            "*** DSound playback failed due to audio decoding errors " +
              audioName
          );
        }
      });
    });
    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,
  digitPreAudios,
  prepareAudioList,
  digitAudios_Gdd,
  digitAudios_nonGdd,
};
