import type GPIO from "../pins"

export const ensure = <T>(value: T, message: string): T => {
  if (value === undefined || value === null) {
    throw new Error(message)
  }

  return value
}

export const random = <T>(arr: ReadonlyArray<T>): T => {
  return arr[Math.floor(Math.random() * arr.length)]!
}

export const ring = async (ringer: GPIO.Output, duration: number, signal?: AbortSignal) => {
  try {
    const endAt = performance.now() + duration
    while (performance.now() < endAt && !signal?.aborted) {
      ringer.value = 1
      await Bun.sleep(50)
      ringer.value = 0
      await Bun.sleep(50)
    }
  } finally {
    ringer.value = 0
  }
}
