import { isMediaDevicesSupported, isValidType } from "./utils.js";
import { useEffect, useRef } from "react";
//#region src/components/QRReader/hooks.ts
const useQRReader = ({ scanDelay: delayBetweenScanAttempts = 500, constraints: video, onResult, videoId }) => {
	const mountedRef = useRef(true);
	useEffect(() => {
		const readQRCode = async () => {
			const { BrowserQRCodeReader } = await import(
				/* webpackChunkName: "zxing" */
				"@zxing/browser"
);
			const codeReader = new BrowserQRCodeReader(void 0, { delayBetweenScanAttempts });
			if (!isMediaDevicesSupported() && onResult) onResult(null, /* @__PURE__ */ new Error("MediaDevices API has no support for your browser. You can fix this by running \"npm i webrtc-adapter\""), codeReader);
			if (video && isValidType(video, "constraints", "object")) codeReader.decodeFromConstraints({ video }, videoId, (result, error, controls) => {
				if (mountedRef.current === false) {
					controls.stop();
					return;
				}
				if (typeof result !== "undefined" && onResult) {
					controls.stop();
					onResult(result, error, codeReader);
				}
			}).catch((error) => {
				if (onResult) onResult(null, error, codeReader);
			});
		};
		mountedRef.current = true;
		readQRCode();
		return () => {
			mountedRef.current = false;
		};
	}, [
		delayBetweenScanAttempts,
		onResult,
		video,
		videoId
	]);
};
//#endregion
export { useQRReader };
