import type { VisualizerDef, VisualizerOptions } from "../visualizers/index.ts";

export const EMPTY_FREQ = new Uint8Array(0);

export function fitCanvas(canvas: HTMLCanvasElement) {
  const container = canvas.parentElement!;

  const scale = Math.min(
    container.clientWidth / canvas.width,
    container.clientHeight / canvas.height,
  );
  canvas.style.width = `${Math.round(canvas.width * scale)}px`;
  canvas.style.height = `${Math.round(canvas.height * scale)}px`;
}

let stopPreview: (() => void) | null = null;

export function startPreview(
  name: string,
  canvas: HTMLCanvasElement,
  fpsSelect: HTMLSelectElement,
  visualizers: Record<string, VisualizerDef>,
  getOpts: () => VisualizerOptions,
) {
  stopPreview?.();
  const fps = Number(fpsSelect.value);
  stopPreview = visualizers[name].preview(canvas, EMPTY_FREQ, getOpts, fps);
}

export function updateCanvas(
  canvas: HTMLCanvasElement,
  resSelect: HTMLSelectElement,
  ratioSelect: HTMLSelectElement,
  select: HTMLSelectElement,
  fpsSelect: HTMLSelectElement,
  visualizers: Record<string, VisualizerDef>,
  getOpts: () => VisualizerOptions,
) {
  const h = Number(resSelect.value);
  canvas.width = h * Number(ratioSelect.value);
  canvas.height = h;
  fitCanvas(canvas);
  startPreview(select.value, canvas, fpsSelect, visualizers, getOpts);
}
