// QRScanner — an OPTIONAL, host-provided capability. The native scanner is implemented by some hosts
// (the le.codes app) and not others (the generic web viewer), so it's gated on host support and throws
// a clear error where it's missing — the same approach as physics (`physicsHasSupport`) and AR
// (`requestCamera`). Ported 1:1 from worker/src/utils/QRScanner.ts.
//
// It lives under `plugins/` rather than the core engine folders to mark it as host-optional. This is a
// *convention*, not a plugin *system* — when there are several of these (NFC, Bluetooth, …) we can
// extract a real mechanism; for one capability that would be premature.

export class QRScanner {
  private readonly _onData: (data: string | null) => void

  /** `onData` fires for every value the scanner decodes (null = a frame with no readable code). */
  constructor(onData: (data: string | null) => void) {
    this._onData = onData
  }

  /** Whether this host provides a native QR scanner (the le.codes app does; many hosts don't). */
  static get isSupported(): boolean {
    return typeof _creatorUtils.openScanner === "function"
  }

  /** Ask for camera access, then open the native scanner. Rejects if the host can't scan or access is denied. */
  async open(): Promise<void> {
    if (!QRScanner.isSupported) {
      throw new Error("QRScanner isn't available on this host — it needs the le.codes app's native scanner.")
    }
    await new Promise<void>((res, rej) => _creator.requestCamera(res, rej))
    await new Promise<void>((res, rej) => _creatorUtils.openScanner(res, rej, this._onData))
  }

  /** Close the scanner and release the camera. */
  close(): void {
    _creatorUtils.closeScanner()
  }
}
