<script setup>
import { ref, onMounted } from 'vue'
import _ from 'cmbsdk-cmbweb';


// reactive state

const ready 		= ref(false)
const status 		= ref('cmbWEB status: ')
const version 		= ref('cmbWEB version: ')
const scanResult 	= ref('')

// functions that mutate state and trigger updates

//informative methods:
function updateReady(ready_arg) {
	ready.value = ready_arg
}
function updateStatus(status_arg) {
	status.value = 'cmbWEB status: ' + status_arg
}
function updateVersion(version_arg) {
	version.value = 'cmbWEB version: ' + version_arg
}
//event listener:
async function scannerReadyListener(e) {
	
	//your code here:
	updateStatus(e.detail); //Prints "Scanner is ready."
	
	//can use mwbScanner.* methods now
	//mwbScanner.scanImage("test_img.png");
	
	updateVersion(mwbScanner.getVersion().cmbWebVersion);
	updateReady(true);
}
//result callback:
function resultCallback(result) {
	
	if (result.type == "Error") scanResult.value = result.type + ": " + result.errorDetails.userFriendly;
	else if (result.type == "Cancel") scanResult.value = "No Barcode.";
	else if (result.type == "NoResult") scanResult.value = "No Barcode.";
	
	else if (result.type == "Multicode")
	{
		let resultCodes_string = "";
		let foundCodes = result.count;
		for (let i = 0; i < foundCodes; i++)
		{
			resultCodes_string += result.codes[i].type + '\n' + result.codes[i].code + '\n';
			
		}
		mwbScanner.beep();
		scanResult.value = result.type + '\n\n' + resultCodes_string;
	}
	else
	{
		mwbScanner.beep();
		scanResult.value = result.type + '\n' + result.code;
		
		//mwbScanner.resumeScanning(); //if using !MWBcloseScannerOnDecode
	}
}
//UI controling methods:
function startScanning() {
	scanResult.value = ''
	mwbScanner.startScanning(resultCallback)
}
function stopScanning() {
	mwbScanner.closeScanner()
}

// lifecycle hooks

onMounted(() => {
	window.mwbScanner = _
	document.addEventListener("scannerModuleLoaded", scannerReadyListener)
})
</script>

<template>
	<button @click="startScanning" :disabled="!ready">Start Scanner</button>
	<button @click="stopScanning" :disabled="!ready">Stop Scanner</button>

	<br>

	<div id="cmbweb-preview-container" style="border:1px solid; position:fixed; top:25%; left:25%; width:50%; height:30%; background-color:gray;"></div>

	<div id="res" style="position:fixed; top:60%; left:25%; width:50%; height:8%;">
	<pre><code>{{ scanResult }}</code></pre>
	</div>

	<br>

	<pre><code>{{ status }}</code></pre>
	<pre><code>{{ version }}</code></pre>
</template>

<style scoped>
pre {
	white-space: pre-wrap;
	word-wrap: break-word;
}
code {
	font-family: Consolas,"courier new";
	color: limegreen;
	background-color: #f1f1f1;
	padding: 2px;
	font-size: 105%;
}
</style>
