import { ProcessorProjectState } from './types';

const clickLengthSeconds = 0.02;
const firstBeatFrequency = 1500;
const otherBeatFrequency = 750;
const frequencyDropAmount = 0.4;
const amplitude = 0.75;

const metronome = (state: ProcessorProjectState, time: number, samplesPerBeat: number, sampleRate: number) => {

  if (time % samplesPerBeat >= clickLengthSeconds * sampleRate) {
    return 0;
  } else {
    const beatNumberInBar = Math.floor((time % (samplesPerBeat * state.beatNumerator)) / samplesPerBeat);
    const clickFrequency = beatNumberInBar === 0 ? firstBeatFrequency : otherBeatFrequency;


    const indexInBeat = time % samplesPerBeat;
    const clickProgress = 1 - (indexInBeat / (clickLengthSeconds * sampleRate));


    const frequency = clickFrequency * ((1 - frequencyDropAmount) + (clickProgress * frequencyDropAmount))

    const currentAmplitude = Math.pow(clickProgress, 2) * amplitude;

    return Math.sin((indexInBeat * frequency) * 2 * Math.PI / sampleRate) * currentAmplitude
  }
}

export default metronome;
