Homepage.registerBrick({
	name:"fi_oulu_MyPlatesByProject",
	title:"My latest plates, by project",
	description:"A list of your most recent plates, by project",
	version:1,
	height:2,
	width:1,
	url:"/api/project/isarchived/0",
	getAll:true,
	sortBy:"name",
	onSuccess:function(transport,box){
		let projects=transport.responseJSON.rows;
		let bb=box.querySelector(".boxbody");
		bb.innerHTML="";
		projects.forEach(function(p){
			if(1*p.owner!==userId){ return; }
			bb.treeItem({ 
				id:'fi_oulu_MyPlatesByProject_proj'+p.id,
				header:'<a href="/project/'+p.id+'">'+p.name+'</a> (mine)',
				record:p,
				updater:Homepage["bricks"]["fi_oulu_MyPlatesByProject"].getPlatesForProject
			});
		});
		projects.forEach(function(p){
			if(1*p.owner===userId){ return; }
			bb.treeItem({ 
				id:'fi_oulu_MyPlatesByProject_proj'+p.id,
				header:'<a href="/project/'+p.id+'">'+p.name+'</a>',
				record:p,
				updater:Homepage["bricks"]["fi_oulu_MyPlatesByProject"].getPlatesForProject
			});
		});
	},

	onFailure:function(transport,box){
		let error="Could not get projects.";
		if(transport.responseJSON && transport.responseJSON.error){
			error=transport.responseJSON.error;
		}
		box.querySelector(".boxbody").innerHTML=error;
	},
	
	getPlatesForProject: function(clicked){
		let treeItem=clicked.closest(".treeitem");
		let projectid=treeItem.record.id;
		new AjaxUtils.Request("/api/plate/projectid/"+projectid+"/ownerid/"+userId+"?pagesize=50&sortby=name&sortdescending=1",{
			method:"get",
			onSuccess:function(transport){ this.getPlatesForProject_onSuccess(transport,treeItem)}.bind(this),
			onFailure:function(transport){ this.getPlatesForProject_onFailure(transport,treeItem)}.bind(this),
		});
	},
	getPlatesForProject_onSuccess: function(transport,treeItem){
		let t=ui.table({
			cellTemplates:['<a href="/plate/{{id}}">{{name}}</a>']
		}, transport.responseJSON, treeItem.querySelector(".treebody") );
		let rows=t.querySelectorAll("tr");
		let last=rows[rows.length-1];
		if(!last.classList.contains("datarow")){
			last.remove();
		}
	},
	getPlatesForProject_onFailure: function(transport,treeItem){
		let error="Could not get plates.";
		if(transport.responseJSON && transport.responseJSON.error){
			error=transport.responseJSON.error;
		}
		treeItem.querySelector(".treebody").innerHTML=error;
	},

});