class Scanner
{
	static api;
	static settings;
	static scanned;
	
	constructor(parent) {
		Scanner.api = parent;
		this.qr = null;
		this.cameras = [];
	}
	
	Start(id, subroute, parser) {
		Scanner.settings = {
			subroute: subroute,
			parser: parser,
			id: id
		};
		Scanner.scanned = {primary: {}, secondary: {}};
		for (let i in parser) {
			if (i!=subroute) {
				Scanner.scanned.secondary[parser[i]] = null;
		} }
		
		// Find already parsed IDs
		const subData = Scanner.api.activeRoute.resourcesIndex[id].data.SUB[parser[subroute]];
		for (let i in subData) {
			Scanner.scanned.primary[subData[i].ID] = true;
		}
		
		this.qr = new QrScanner(
    	document.getElementById("qrscanner_video"),
    	Scanner.parse,
    	{returnDetailedScanResult: true, highlightScanRegion: true, highlightCodeOutline: true}
		);
		if (QrScanner.hasCamera()) {
			let _this = this;
  		QrScanner.listCameras(true)
  			.then(result => _this.cameras = result)
  			.catch(error => alert(error || 'Camera detection failed.'));
		}
	  this.cameraIndex = 0;
		document.getElementById("qrscanner_text").innerHTML = "";
		
		this.qr.start();
	}
	Stop() {
		this.qr.stop();
		this.qr.destroy();
		this.qr = null;
	}
	SwitchCamera() {
		if (this.qr!==null && QrScanner.hasCamera()) {
		  ++this.cameraIndex;
		  if (this.cameraIndex>=this.cameras.length) {
		    this.cameraIndex = 0;
		  }
		  this.qr.setCamera(this.cameras[this.cameraIndex].id);
		}
	}
	static parse(result) {
		let scan = result.data.split("/");
		if (scan.length==3) {
			let route = scan[1];
			let subid = scan[2];

			// Is it a route we should parse?
			if (typeof(Scanner.settings.parser[route])!="undefined") {
				const marker = Scanner.settings.parser[route];

				// Is it the primary route and if yes, has this ID been parsed before?			
				if (route==Scanner.settings.subroute && typeof(Scanner.scanned.primary[subid])=="undefined") {
					Scanner.scanned.primary[subid] = true;
					
					let index = -1;
					
					const options = Scanner.api.activeRoute.options[marker];
					for (let i in options) {
						if (options[i].ID==subid) {
							index = i;
							break;
					} }
					// Has the ID been found?
					if (index>=0) {
						document.getElementById("qrscanner_text").innerHTML += options[index].NAME + "<br />";
						Scanner.api.Request("POST", Scanner.scanned.secondary, Scanner.settings.id, Scanner.settings.subroute, subid);
					}
				} else if(route!=Scanner.settings.subroute) { // Is it a secondary field?
					Scanner.scanned.secondary[marker] = subid;
	}	}	}	}
}

