import * as VAPI from "../mod.ts";
import * as VScript from "http://172.16.0.12/bladerunner_sdk/vscript@2.5.2/deno/release/mod.ts";
export type AudioRef1130 = VScript.RefinedIndexedNonmutatingReference<VScript.VSocket, "channels", "Audio::Data::Essence", VScript.Referenceable<"Audio::Data::Essence"> & VAPI.AT1130.Audio.Essence, null | [
  null | string,
  number,
  boolean,
  [
    number,
    number,
    number,
    number,
    number
  ]
], null | VAPI.Audio.Channel>;
export async function set_input(
  obj: VAPI.AT1130.AudioEngine.Compressor |
    VAPI.AT1130.AudioEngine.Delay |
    VAPI.AT1130.AudioEngine.Filter |
    VAPI.AT1130.AudioEngine.Loudness |
    VAPI.AT1130.AudioEngine.TruePeak |
    VAPI.AT1130.AudioEngine.DownMix |
    VAPI.AT1130.AudioEngine.MidSide,
  src: null | VAPI.AT1130.Audio.Essence | (null | AudioRef1130)[],
  pars?: {
    start?: number,
    channels?: number
  }) {
  const start = pars?.start ?? 0;
  if (!Number.isInteger(start) || start < 0) throw new Error("start must be an integer >= 0");
  const max_inputs = 16;
  let update: (null | AudioRef1130)[] = Array(max_inputs).fill(null);
  if (src instanceof VAPI.AT1130.Audio.Essence) {
    const channels = pars?.channels ?? max_inputs;
    if (!Number.isInteger(channels) || channels <= 0 || channels > max_inputs) throw new Error(`channels must be an integer between 1 and ${max_inputs}`);
    if (start > (max_inputs - channels)) throw new Error("the range start and channels is out of bounds");
    for (let i = 0; i < channels; ++i)
      update[i] = src.channels.reference_to_index(start + i);
  } else if (src !== null) {
    if (start >= src.length) new Error("start is out of bounds");
    const max_channels = Math.min(max_inputs, src.length - start);
    const channels = pars?.channels ?? max_channels;
    if (!Number.isInteger(channels) || channels <= 0 || channels > max_channels) throw new Error("channels is out of bounds");
    for (let i = 0; i < channels; ++i)
      update[i] = src[start + i];
  }
  await obj.inputs.write(update);
}
