Homepage.registerBrick({
	name:"fi_oulu_PlateBulkDestroy",
	title:"Plate destruction",
	description:"Mark several plates as destroyed by scanning their barcodes.",
	version:1,
	height:1,
	width:1,
	url:"/api/",

	onSuccess:function(transport,box){
		let bb=box.querySelector(".boxbody");
		bb.innerHTML="";
		let frm=box.form({
			action:'#',
			method:'patch'
		});
		frm.textField({ label:"Scan plate to destroy", name:"fi_oulu_PlateBulkDestroy_name" });
		frm.createButton();
		let labels=frm.querySelectorAll("label")
		labels[labels.length-1].style.display="none"; //need it to prevent autosubmit, but hide it.
		let msg=document.createElement("label");
		msg.id="fi_oulu_PlateBulkDestroy_msg";
		msg.innerHTML='Set your barcode scanner to send Enter after scanning';
		msg.style.textAlign="center";
		frm.appendChild(msg);
		frm.onsubmit=function(){ this.destroyPlate(); return false; }.bind(this);
	},
	
	destroyPlate:function(){
		let plateBarcode=document.getElementById("fi_oulu_PlateBulkDestroy_name").value.trim();
		if(!plateBarcode){ return false; }
		let msg=document.getElementById("fi_oulu_PlateBulkDestroy_msg");
		msg.innerHTML="<span>Updating...</span>";
		msg.classList.remove("invalidfield");
		msg.classList.add("updating");
		new AjaxUtils.Request("/api/plate/destroyByName/"+plateBarcode,{
			'method':'patch',
			'parameters':{
				csrfToken:csrfToken
			},
			'onSuccess':this.destroyPlate_onSuccess,
			'onFailure':this.destroyPlate_onFailure
		});
	},
	
	destroyPlate_onSuccess:function(transport){
		let msg=document.getElementById("fi_oulu_PlateBulkDestroy_msg");
		let txt="Plate destroyed";
		if(304===transport.status){
			txt="Plate already destroyed";
		} else if(transport.responseJSON && transport.responseJSON["updated"]){
			txt="Plate "+transport.responseJSON["updated"].name+" destroyed";
		}
		msg.innerHTML=txt;
		msg.classList.remove("updating");
		document.getElementById("fi_oulu_PlateBulkDestroy_name").value="";
		document.getElementById("fi_oulu_PlateBulkDestroy_name").focus();
	},
	destroyPlate_onFailure:function(/*transport*/){
		let msg=document.getElementById("fi_oulu_PlateBulkDestroy_msg");
		msg.innerHTML="Could not destroy plate";
		msg.classList.add("invalidfield");
		msg.classList.remove("updating");
		document.getElementById("fi_oulu_PlateBulkDestroy_name").value="";
		document.getElementById("fi_oulu_PlateBulkDestroy_name").focus();
	},
	
	showHelp:function(){
	
	}
	
});