import { isMobile } from "./utilities.js";

const useSDKOnCamera = (videoSelector, discardElSelector, callback) => {
    
    async function startStream(stream) {
        const video = document.querySelector(videoSelector);
        video.srcObject = stream;
        try {
            await video.play();
        } catch (e) {
            console.log("Error: ", e.name, "message: ", e.message);
        }

        //Due to safari issues, first frame is discarded
        const discardCanvas = document.querySelector(discardElSelector);
        const discardContext = discardCanvas.getContext("2d");
        discardContext.drawImage(video, 0, 0);

        video.onended = () => {
            video.play();
        };

        setTimeout(callback, 1000);
    }

    const openCamera = (_constraints = undefined) => {
        let constraints = _constraints
            ? Object.assign({}, _constraints)
            : {
                  video: {
                      width: { min: 640, ideal: 1440, max: 1920 },
                      height: { min: 480, ideal: 1080, max: 1440 },
                  },
                  audio: false,
              };

        navigator.mediaDevices
            .enumerateDevices()
            .then((deviceInfos) => {
                if (isMobile()) {
                    for (let i = 0; i !== deviceInfos.length; ++i) {
                        let deviceInfo = deviceInfos[i];

                        if (
                            deviceInfo.kind.includes("videoinput") &&
                            (deviceInfo.label.includes("front") || deviceInfo.label.includes("Front"))
                        ) {
                            constraints = {
                                ...constraints,
                                deviceId: deviceInfo.deviceId,
                            };
                            break;
                        }
                    }
                }

                navigator.mediaDevices.getUserMedia =
                    navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

                navigator.mediaDevices
                    .getUserMedia(constraints)
                    .then(startStream)
                    .catch((error) => {
                        console.error("navigator.MediaDevices.getUserMedia error: ", error.message, error.name);
                    });
            })
            .catch((error) => {
                console.error("navigator.MediaDevices.getUserMedia error: ", error.message, error.name);
            });
    };

    return openCamera;
};

export default useSDKOnCamera;
