import {createCustomOsc} from './oscillator'

export function createChorus(ctx: Object) 
{
  const merger = ctx.createChannelMerger(2)
  const input = ctx.createGain()
  const output = ctx.createGain()
  const feedbackL = ctx.createGain()
  const feedbackR = ctx.createGain()
  const delayL = ctx.createDelay()
  const delayR = ctx.createDelay()
  const lfoLGain = ctx.createGain()
  const lfoRGain = ctx.createGain()
  const lfoL = createCustomOsc(ctx)
  const lfoR = createCustomOsc(ctx)

  input.connect(output)
  input.connect(delayL)
  input.connect(delayR)

  lfoL.connect(lfoLGain)
  lfoL.start(0)

  lfoR.connect(lfoRGain)
  lfoR.start(0)

  lfoRGain.connect(delayR.delayTime)
  lfoLGain.connect(delayL.delayTime)
  lfoLGain.connect(lfoR.frequency)

  delayL.connect(feedbackL)
  delayR.connect(feedbackR)

  feedbackL.connect(delayL)
  feedbackR.connect(delayR)

  feedbackL.connect(merger, 0, 0)
  feedbackR.connect(merger, 0, 1)

  merger.connect(output)

  const setters = {
    frequency(value) {
      lfoL.frequency.value = value
      lfoR.frequency.value = value
    },
    feedback(value) {
      feedbackL.gain.value = value
      feedbackR.gain.value = value
    }
  }

  return {
    __setters: setters,
    input,
    connect(node) { output.connect(node) },
    init(patch) {
      lfoL.init({
        frequency: patch.frequency,
        type: patch.type,
        phase: 180
      })

      lfoR.init({
        frequency: patch.frequency,
        type: patch.type,
        phase: 0
      })

      // TODO: Add public access to chorus depth here
      input.gain.value = 0.6934
      lfoLGain.gain.value = 0.002
      lfoRGain.gain.value = 0.002

      feedbackL.gain.value = patch.feedback
      feedbackR.gain.value = patch.feedback

    },
    set(key, val) {
      setters[key](val)
    }
  }
}