import { Injectable } from '@angular/core';
import { AppStorage } from 'src/app/shared/app-storage';

@Injectable({
  providedIn: 'root',
})
export class AudioService {
  public playSound(sound: Sounds) {
    gainNode.gain.value = this.getVolume();
    play(sound);
  }

  private getVolume(): number {
    let volume = AppStorage.getItem('volume');
    if (volume) {
      return parseFloat(volume);
    } else {
      return 1;
    }
  }
}

export enum Sounds {
  NOTIFICATION = '/assets/sounds/noti_2.mp3',
  BACKGROUND_NOTIFICATION = '/assets/sounds/noti_1.mp3',
}

// https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API
// https://codepen.io/kslstn/pen/pagLqL

// We can not use HTMLAudioElement because it stops the the media players on iOS, iPhone
// so instead we create an AudioContext with AudioBufferSourceNode

const audioContext = new AudioContext();
const gainNode = audioContext.createGain();
gainNode.gain.value = 1;

let bufferedSounds: { [key in Sounds]?: AudioBuffer } = {};

let loadSoundAsBuffer = (sound: Sounds) => {
  return window
    .fetch(sound)
    .then((response) => response.arrayBuffer())
    .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer));
};

Object.values(Sounds).forEach((s: Sounds) => {
  loadSoundAsBuffer(s).then((arrayBuffer) => {
    bufferedSounds[s] = arrayBuffer;
  });
});

let play = (sound: Sounds) => {
  let audioBuffer = bufferedSounds[sound];
  if (audioBuffer) {
    let audioSource = audioContext.createBufferSource();
    audioSource.buffer = audioBuffer;
    audioSource.connect(audioContext.destination);
    audioSource.start();
  } else {
    console.warn('sound did not loaded yet');
  }
};
