const video = document.getElementById('video'); 
const button = document.getElementById('button'); 

let currentStream;
var glbFM = "";

function stopMediaTracks(stream) {
	stream.getTracks().forEach(track => {
		track.stop();
	});
}  

button.addEventListener('click', event => {
	if($("#button").text()=="Open Camera"){
		callCam();
	}else{
		capture();
	} 
});

video.addEventListener('click', event => {
	if(glbFM!=""){
		capture();
	}
});
 
function callCam(){
	$("#button").text("Capture"); 
	$("#img").attr("src", "");
	$("#img").css("display", "none");
	$("#video").css("display", "inline-block");

	if (typeof currentStream !== 'undefined') {
		stopMediaTracks(currentStream);
	}

	const videoConstraints = {}; 
	glbFM = 'user';

	videoConstraints.facingMode = glbFM;
	const constraints = {
		video: videoConstraints,
		audio: false
	};  

	navigator.mediaDevices
	.getUserMedia(constraints)
	.then(stream => {
		currentStream = stream;
		video.srcObject = stream;
		return navigator.mediaDevices.enumerateDevices();
	})
	.catch(error => {
		console.error(error);
	});
}
 
function capture(){
	$("#video").css("display", "none");
	$("#img").css("display", "inline-block");
	const img = document.querySelector("#img");
	const canvas = document.createElement("canvas");

	canvas.width = video.videoWidth;
	canvas.height = video.videoHeight;
	canvas.getContext("2d").drawImage(video, 0, 0);
	// Other browsers will fall back to image/png
	if(canvas.toDataURL("image/wedp")!="data:,"){
		$("#video").css("display", "none");
		$("#img").css("display", "inline-block");
		img.src = canvas.toDataURL("image/webp");
		stopMediaTracks(currentStream);
		$("#button").text("Open Camera"); 
		glbFM = '';
	}
} 