var soloud = use('soloud')
var tween = use('tween')
var io = use('io')
var res = use('resources')
var doc = use('doc')

soloud.init();

var audio = {};
audio[doc.sym] = `Audio docs.`

var pcms = {};

audio.pcm = function pcm(file)
{
  file = res.find_sound(file);
  if (!file) throw new Error(`Could not findfile ${file}`);
  if (pcms[file]) return pcms[file];
  var bytes = io.slurpbytes(file)
  var newpcm = soloud.load_wav_mem(io.slurpbytes(file));
  pcms[file] = newpcm;
  return newpcm;
}

audio.play = function play(file) {
  var pcm = audio.pcm(file);
  if (!pcm) return;
  return soloud.play(pcm);
};
audio.play[doc.sym] = `Given a file path, plays a sound. Returns a sound object.`

audio.cry = function cry(file) {
  var voice = audio.play(file);
  if (!voice) return;
  return function() {
    voice.stop();
    voice = null;
  }
};
audio.cry[doc.sym] =
`Given a file path, plays a sound. Invoke the returned object to stop it.`

var song;

// Play 'file' for new song, cross fade for seconds
audio.music = function music(file, fade = 0.5) {
  if (!file) {
    if (song) song.volume = 0;
    return;
  }

  if (!fade) {
    song = audio.play(file);
    song.loop = true;
    return;
  }

  if (!song) {
    song = audio.play(file);
    song.volume = 1;
    //    tween.tween(song,'volume', 1, fade);
    return;
  }

  var temp = audio.play(file);
  if (!temp) return;

  temp.volume = 1;
  var temp2 = song;
  //  tween.tween(temp, 'volume', 1, fade);
  //  tween.tween(temp2, 'volume', 0, fade);
  song = temp;
  song.loop = true;
};
audio.music[doc.sym] = `Play the given music file, with an optional cross fade. The song will loop. When this is invoked again, the previous music is replaced.`

var ss = use('sdl_audio')

var feeder = ss.open_stream("playback")

feeder.set_format({format:"f32", channels:2,samplerate:44100})

feeder.resume()

var FRAMES = 1024
var CHANNELS = 2
var BYTES_PER_F = 4
var SAMPLES = FRAMES * CHANNELS
var CHUNK_BYTES = FRAMES * CHANNELS * BYTES_PER_F

var mixview = new Float32Array(FRAMES*CHANNELS)
var mixbuf = mixview.buffer

function pump()
{
  if (feeder.queued() < CHUNK_BYTES*3) {
    var mm = soloud.mix(FRAMES)
    feeder.put(mm)
  }

  $_.delay(pump, 1/240)
}

pump()

return audio;
