// Device camera → a still-photo File. Ported from worker/src/utils/CameraViewer.ts. Permission is
// requested through the engine bridge's `requestCamera` (same as QRScanner); the live preview and the
// capture go through `_creatorUtils.camera*`. `takePhoto()` returns a File (a host buffer handle), so
// the shot can be used as a texture (`Texture2D.load(file)`), uploaded via FormData, or shared.

import { File } from "./fetch"

export class CameraViewer {
  /** Ask for camera permission and start the live preview (default: the back camera). */
  static async open(facingMode: "front" | "back" = "back"): Promise<void> {
    await new Promise<void>((res, rej) => _creator.requestCamera(res, rej))
    await new Promise<void>((res, rej) => _creatorUtils.cameraOpen(facingMode, res, rej))
  }

  /** Switch between the front and back camera while the preview is open. */
  static setFacingMode(facingMode: "front" | "back"): void {
    _creatorUtils.cameraSetFacingMode(facingMode)
  }

  /** Capture a still frame as an image File (host-encoded). */
  static takePhoto(): Promise<File> {
    return new Promise<File>((res, rej) => {
      _creatorUtils.cameraTakePhoto((bufferId, name, size) => res(new File(bufferId, name, size)), rej)
    })
  }

  /** Stop the preview and release the camera. */
  static close(): void {
    _creatorUtils.cameraClose()
  }
}
