import copyArraySection from '../utils/copyArraySection';
import makeAudioBuffer from '../utils/makeAudioBuffer';

export default (audioBuffer: AudioBuffer, insertStartSamples: number, insertLength: number) => {
  const newAudioBuffer = makeAudioBuffer({
    length: audioBuffer.length + insertLength,
    sampleRate: audioBuffer.sampleRate,
    numberOfChannels: audioBuffer.numberOfChannels
  });

  for(let c = 0; c < audioBuffer.numberOfChannels; c ++) {
    const originalChannelData = audioBuffer.getChannelData(c);
    const outputChannelData = newAudioBuffer.getChannelData(c);

    // write samples from the original array, up to the insertStart point
    copyArraySection(originalChannelData, outputChannelData, insertStartSamples, 0, 0);

    // write samples from the original array, reading from insertStartSamples in the original array
    // and writing with an insertStart+insertLength offset
    copyArraySection(originalChannelData, outputChannelData, audioBuffer.length - insertStartSamples, insertStartSamples, insertStartSamples + insertLength);
  }

  return newAudioBuffer;
}
