Homepage.registerBrick({
	name:"fi_oulu_Containers",
	title:"Container management",
	description:"For technicians. Quickly register pins, pucks, etc., by barcode, or empty them after a shipment.",
	version:1,
	height:1,
	width:1,
	url:"/api/containertype",
	getAll:true,
	sortBy:"name",

	onSuccess:function(transport,box){
		box.containertypes=transport.responseJSON.rows;
		box.containertypes.sort(function(a,b){
			if(a.containercategoryname<b.containercategoryname){ return -1; }
			if(a.containercategoryname>b.containercategoryname){ return 1;  }
			if(a.name<b.name){ return -1; }
			if(a.name>b.name){ return 1;  }
			return 0;
		});
		if(!isAdmin && !isTechnician && !isShipper){
			this.showContainerCreate();
		} else {
			this.showMenu();
		}
	},
	
	showMenu:function(){
		let box=document.getElementById("fi_oulu_Containers");
		let title=box.querySelector("h2");
		title.innerHTML="Container management";
		title.onclick=this.showMenu;
		title.style.cursor="pointer";
		let bb=box.querySelector(".boxbody");
		bb.innerHTML="";
		let frm=box.form({
			action:'#',
			method:'post'
		});
		let ff=frm.formField({ label:'Register new containers',content:'&nbsp;' });
		ff.onclick=this.showContainerCreate;
		ff.style.cursor="pointer";
		ff=frm.formField({ label:'Help',content:'&nbsp;' });
		ff.onclick=this.showHelp;
		ff.style.cursor="pointer";
	},
	
	/*
	 * Container creation
	 */
	
	showContainerCreate:function(){
		let box=document.getElementById("fi_oulu_Containers");
		let title=box.querySelector("h2");
		title.innerHTML="Container management &bull; New containers";
		let bb=box.querySelector(".boxbody");
		bb.innerHTML="";
		let frm=box.form({
			action:'/api/container/',
			method:'post'
		});
		frm.hiddenField('projectid',window["sharedProject"]['id']);
		frm.roleField({
				label:"Container type", 
				name:'containertypeid', 
				otherType:'containertype',
				labelField:'name',
				headers:['Name','Category'],
				cellTemplates:['{{name}}','{{containercategoryname}}']
		});
		frm.textField({ label:"Barcode", name:'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_Containers_msg";
		msg.innerHTML='Set your barcode scanner to send Enter after scanning';
		msg.style.textAlign="center";
		frm.appendChild(msg);
		frm.onsubmit=function(){ this.createContainer(frm); return false; }.bind(this);
		frm.name.focus();
	},
	createContainer:function(frm){
		let barcode=frm.name.value.trim();
		let containertypeid=frm.containertypeid.value;
		let msg=document.getElementById("fi_oulu_Containers_msg");
		if(""===barcode || ""===containertypeid){
			msg.innerHTML="<span>Type and barcode are required.</span>";
			msg.classList.add("invalidfield");
			return false;
		}
		if(!isAdmin && !isTechnician && !isShipper){
			let containerType=frm.containertypeid.closest("label").roleRecord;
			if(1!==1*containerType["userscancreate"]){
				msg.innerHTML="<span>Only technicians and shippers can create a "+containerType.containercategoryname.toLowerCase()+".</span>";
				msg.classList.add("invalidfield");
				return false;
			}
		}
		msg.innerHTML="<span>Creating..."+frm.name.value+"</span>";
		msg.classList.remove("invalidfield");
		msg.classList.add("updating");
		frm.request({
			onSuccess:function(transport){ this.createContainer_onSuccess(transport, frm); }.bind(this),
			onFailure:function(transport){ this.createContainer_onFailure(transport, frm); }.bind(this)
		});
		return false;
	},
	createContainer_onSuccess:function(transport, frm){
		let created=transport.responseJSON.created;
		let msg=document.getElementById("fi_oulu_Containers_msg");
		msg.innerHTML='<span>'+frm.containertypeid.closest("label").roleRecord.name+' <a href="/container/'+created.id+'">'+created.name+'</a> created.</span>';
		msg.classList.remove("updating");
		frm.name.value="";
		frm.name.focus();
	},
	createContainer_onFailure:function(transport, frm){
		if(401===transport.status){ return ui.handleSessionExpired(); }
		let txt=transport.responseText;
		let err;
		if(-1!==txt.indexOf("may already exist")){
			err='Container called '+frm.name.value+' already exists.';
		} else {
			if(transport.responseJSON && transport.responseJSON.error){
				txt=transport.responseJSON.error;
			}
			err='Could not create '+frm.containertypeid.closest("label").roleRecord.name+' '+frm.name.value;
			alert("Could not create. The server said:\n\n"+txt);
		}
		let msg=document.getElementById("fi_oulu_Containers_msg");
		msg.innerHTML='<span>'+err+'</span>';
		msg.classList.add("invalidfield");
		msg.classList.remove("updating");
		frm.name.value="";
		frm.name.focus();
	},
	
	/*
	 * Help
	 */
	 showHelp: function(){
		let box=document.getElementById("fi_oulu_Containers");
		let title=box.querySelector("h2");
		title.innerHTML="Container management &bull; Help";
		let bb=box.querySelector(".boxbody");

		let txt='<h3>Container management</h3>';
		txt+='<p>This brick lets you work with containers other than crystallization plates, for example pins, pucks, and dewars. Plates should not be created this way.</p>';
		txt+='<p>This is mainly intended for lab technicians. However, regular IceBear users may have permission to create some kinds of container. Technicians will see a menu of options, but regular users will only see the container creation form.</p>';
		txt+='<p>It is assumed that your barcode scanner sends a carriage return after a successful scan. To test this, open up your favourite text editor and scan a barcode several times; you should see each scan appearing on a separate line. See your scanner\'s manual for details on configuring this. (You will probably need to scan a specific barcode found within the manual.)</p>';
		
		txt+='<h3>Creating new containers</h3>';
		txt+='<p>Here, you can quickly create many containers of the same type. This is useful when first setting up IceBear, and when you buy new containers (say, a box of pins).</p>';
		txt+='<p>First, specify the type of container you want to create. Click the <strong>Change...</strong> button, then choose the type from the list.</p>';
		txt+='<p>Then, click in the barcode box and scan the barcode of your first new container.</p>';
		txt+='<p>Non-technicians may not be allowed to create every kind of container. If you don\'t have permission, you will get a message telling you this.</p>';
		txt+='<p>If a container with that barcode already exists, the new container will not be created, and you will see an error message. It is assumed that containers of different types will not have the same barcode.</p>';
		txt+='<p>If creation succeeds, you will see a confirmation message. There is a link to the container\'s IceBear page.</p>';
		txt+='<p>To create more containers of the same type, simply scan all their barcodes. The container type will stay the same until you change it.</p>';

		bb.innerHTML=txt;
	 },
	
});