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

const threshold = wavtool.numberSetting({ name: 'Threshold', default: 0.3, min: 0, max: 1 });
const ratio = wavtool.numberSetting({ name: 'Ratio', default: 0.5, min: 1, max: 1/16 });
const attack = wavtool.numberSetting({ name: 'Attack', default: 0.01, min: 0.001, max: 1, exponential: true });
const release = wavtool.numberSetting({ name: 'Release', default: 0.3, min: 0.001, max: 1, exponential: true });

let gain = 1;

project.mapSelectedSamples((sample) => {
  const amplitude = Math.abs(sample);
  const attackRate = 1/(attack * project.sampleRate);
  const releaseRate = 1/(release * project.sampleRate);

  // figure out the ideal gain from the current amplitude, ratio, and threshold
  const targetGain = amplitude > threshold
    ? threshold + (ratio * (amplitude - threshold))
    : 1;

  // are we attacking or releasing?
  let delta = targetGain < gain ? attackRate : releaseRate;

  // move gain towards the target
  gain = ((1 - delta) * gain) + (delta * targetGain);

  return sample * gain;
});
