/// <reference path="../CommandGlobals.d.ts" />

const frequency = wavtool.frequencySetting({
  name: 'Frequency',
  default: 1000
});

const highpass = wavtool.booleanSetting({
  name: 'Mode',
  trueLabel: 'Highpass',
  falseLabel: 'Lowpass',
  default: false
});

project.mapSelectedChannels(
  (channelData, selectionStart, selectionEnd) => {
    const samplesToAverage = Math.floor((1 / frequency) * project.sampleRate);
    const newChannelData = new Float32Array(channelData);

    // Iterate through selected samples
    for (let writeIndex = selectionStart; writeIndex < selectionEnd; writeIndex ++) {
      // Read a bubble of samples around the current sample
      const readStart = Math.max(0, Math.round(writeIndex - (samplesToAverage/2)));
      const readEnd = Math.min(channelData.length - 1, Math.round(writeIndex + (samplesToAverage/2)));

      // Average the position of samples in the bubble
      let sum = 0;
      for (let readIndex = readStart; readIndex < readEnd; readIndex ++) {
        sum += channelData[readIndex];
      }
      const average = sum / (readEnd - readStart);

      // Write to the output float32array
      newChannelData[writeIndex] = highpass
        ? channelData[writeIndex] - average // In highpass mode, return (original signal) minus (slow-moving part of the signal)
        : average; // in lowpass mode, return just the slow-moving part of the signal
    }

    return newChannelData;
  }
);
