var QRCodeReader, selectedDeviceId, videoId, videoBlockId, resultBlock; 

function decodeOnce(QRCodeReader, selectedDeviceId, callback) 
{
	QRCodeReader.decodeFromVideoDevice(selectedDeviceId, videoId, (result, err) => 
	{
		if (result) 
		{
			findProduct(result.text, callback)
		}
		if (err && !(err instanceof ZXing.NotFoundException)) 
		{
			console.error(err);
			document.getElementById('result-block').textContent = err;
		}
	});
}

window.addEventListener('load', function () 
{
	//---------- QR CODES
	QRCodeReader = new ZXing.BrowserMultiFormatReader()
	QRCodeReader.getVideoInputDevices()
	.then((videoInputDevices) => 
	{
		selectedDeviceId = videoInputDevices[videoInputDevices.length - 1].deviceId;
		startScanner();
	})
	.catch((err) => 
	{
		console.error(err)
	})
})

function setResultNormal(){document.getElementById(resultBlock).style.backgroundColor = 'white';}

function setResultError()
{
	document.getElementById(resultBlock).style.backgroundColor = '#009fe0';
}

function checkErrors()
{
	var obj = document.getElementById(resultBlock);
	var arr = obj.getElementsByClassName('error');	
	setResultNormal();
	if (arr.length > 0) 
	{
		var input = 'edtBarcodeNo';
		deleteCookie(input);
		document.getElementById(input).value = ''; //clear the text because it is an invalid code.
		setResultError();
	}
	document.getElementById('btnClearSpl').style.display = 'block';
}

function clearBlock()
{
	resetScanner();
	setResultNormal();
	var obj = document.getElementById('result-block');
	var input = 'edtBarcodeNo';
	var inpobj = document.getElementById(input);
	deleteCookie(input);
	if (obj !== null) obj.innerHTML = '';
	if (inpobj !== null) inpobj.value = ''; //clear the text because it is an invalid code.
	document.getElementById('btnClearSpl').style.display = 'none';
}

function setIds()
{
	videoBlockId	= 'scan-block';
	videoId 		= 'video-scan';
	resultBlock 	= 'result-block';
}

function showInputField()
{
	setIds();
	resetScanner();
	document.getElementById(resultBlock).style.display  = 'none';
}

function scanQRBarcodes(callback)
{
	decodeOnce(QRCodeReader, selectedDeviceId, callback);
}

function startScanner(callback)
{
	setIds();
	document.getElementById(videoBlockId).style.display = 'block';
	document.getElementById(resultBlock).style.display	= 'none';
	scanQRBarcodes(callback);
}

function resetScanner()
{
	if (videoId 		!== undefined) 	document.getElementById(videoBlockId).style.display = 'none';
	if (resultBlock 	!== undefined) 	document.getElementById(resultBlock).style.display 	= 'block';
	if (QRCodeReader 	!== undefined) 	QRCodeReader.reset();
	checkErrors();
}