import { TimeSelection } from '../../types';
import copyArraySection from '../utils/copyArraySection';
import makeAudioBuffer from '../utils/makeAudioBuffer';

export default (audioBuffer: AudioBuffer, [selectionStartSamples, selectionEndSamples]: TimeSelection) => {
  const editLength = selectionEndSamples - selectionStartSamples;

  if (editLength <= 0 || selectionStartSamples > audioBuffer.length || selectionEndSamples < 0) {
    return audioBuffer;
  }

  const targetPostEditLength = Math.max(audioBuffer.length, selectionEndSamples) - editLength;

  if (targetPostEditLength <= 0) {
    // return a silent, one-sample-long buffer.
    return makeAudioBuffer({
      length: 1,
      sampleRate: audioBuffer.sampleRate,
      numberOfChannels: audioBuffer.numberOfChannels
    });
  }

  const newAudioBuffer = makeAudioBuffer({
    length: targetPostEditLength,
    sampleRate: audioBuffer.sampleRate,
    numberOfChannels: audioBuffer.numberOfChannels
  });

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

    // copy [0 ... selectionStartSamples] from old data into the same positions in new data
    copyArraySection(oldChannelData, newChannelData, selectionStartSamples, 0, 0);

    // copy [selectionEndSamples ... end] from old data, into [selectionStartSamples ... end] in new data
    copyArraySection(oldChannelData, newChannelData, audioBuffer.length - selectionEndSamples, selectionEndSamples, selectionStartSamples);
  }

  return newAudioBuffer;
};
