const phaseInput = new Float64Array(bufferSize);
const ReadOscilloscopeInputs = ({ input, frequency, trigger, inputOscilloscope }) => {
  const lastWriteIndex = useVal(0);
  const oscillator = useOscillator(Waveform.Sawtooth);
  const oscillatorOutput = oscillator(frequency, phaseInput, trigger);
  const lastOscillatorOutput = useVal(-1);
  for (let i = 0; i < input[0].length; i ++) {
    if (lastWriteIndex.current < inputOscilloscope.length) {
      inputOscilloscope[lastWriteIndex.current] = input[0][i];
      lastWriteIndex.current ++
    } else if (lastOscillatorOutput.current <= 0 && oscillatorOutput[i] > 0) {
      lastWriteIndex.current = 0;
    }
    lastOscillatorOutput.current = oscillatorOutput[i];
  }
}

const Visualizer = (ctx, settings) => {
  const h = ctx.canvas.height;
  const w = ctx.canvas.width;
  const imageData = ctx.getImageData(0, 0, w, h);
  ctx.clearRect(0, 0, w, h);
  ctx.putImageData(imageData, 0, -1);
  ctx.fillStyle = `${gray100}42`;
  let max = 0;
  for (let i = 0; i < settings.inputOscilloscope.length; i ++) {
    max = Math.max(max, Math.abs(settings.inputOscilloscope[i]));
  }
  ctx.strokeStyle = `rgba(
    ${Math.floor((settings.frequency + 80) % 255)},
    ${Math.floor((settings.frequency + 160) % 255)},
    ${Math.floor(settings.frequency % 255)},
    ${max}
  )`;

  //  ctx.fillRect(0, 0, w, h);
  ctx.beginPath();
  ctx.moveTo(-w, h);
  ctx.lineTo(-w, 9*h/10);
  for (let i = 0; i < settings.inputOscilloscope.length; i ++) {
    ctx.lineTo(
      (i / settings.inputOscilloscope.length) * w,
      9*h/10 + (settings.inputOscilloscope[i] * 0.2 * h/2)
    );
  }
  ctx.lineTo(w*2, h/2);
  ctx.lineTo(w*2, h);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
};

this.constructDevice = () => constructPerBufferDevice({
  implementation: ReadOscilloscopeInputs,
  inputs: {
    input: stereo('In'),
    frequency: expose(frequencySetting('Frequency', 1000)),
    trigger: expose(zeroOneSetting('Trigger', 0)),
  },
  sharedArrays: {
    inputOscilloscope: 1024
  },
  layout: row([
    pinnable(canvas(
      'main',
      Visualizer,
      400,
      200
    ))
  ])
});
