<?php
/** @var array $data The object we are going to view */
$pageTitle='Imager: '.$data['friendlyname'];
include realpath(__DIR__).'/../../core/_common/header.php'; ?>
<script type="text/javascript">
let manualImagingAllowed=<?php echo (config::get('imaging_allowmanual')) ? 'true' : 'false'; ?>;
window.addEventListener('DOMContentLoaded',function(){

	ui.grid();

	let detailsBox=grid.box({
		classes:'r1 c1 h3 w1',
		title:'Details'
	});

	let frm=detailsBox.form({
		action:'/api/imager/'+data['id'],
		method:'post',
	});
	frm.textField({ label:"Serial", name:'name', value:data['name'],readonly:!isAdmin });
	frm.textField({ label:"Friendly name", name:'friendlyname', value:data['friendlyname'],readonly:!isAdmin });
	frm.textField({ label:"Manufacturer", name:'manufacturer', value:data['manufacturer'],readonly:!isAdmin });
	frm.textField({ label:"Temperature", name:'temperature', value:data['temperature'],readonly:!isAdmin });
	frm.textField({ label:"Plate capacity", name:'platecapacity', value:data['platecapacity'],readonly:!isAdmin });
	frm.textField({ label:"Alert level", name:'alertlevel', value:data['alertlevel'],readonly:!isAdmin });
	frm.textField({ label:"Warning level", name:'warninglevel', value:data['warninglevel'],readonly:!isAdmin });
	frm.textField({ label:"Active plates", name:'platesactive', value:data['platesactive'],readonly:true });
	frm.textField({ label:"Expired plates", name:'platesexpired', value:data['platesexpired'],readonly:true });
	if(manualImagingAllowed){
		frm.checkbox({ label:'Manual imaging', name:'manualimaging', value:data['manualimaging'],readonly:!isAdmin });
	}
    frm.checkbox({ label:'In use', name:'isinuse', value:data['isinuse'],readonly:!isAdmin });

	let ts=grid.tabSet({ classes:"r1 c2 h3 w2"});

	let headerTemplates;
	let cellTemplates;

 	headerTemplates=['Plate', 'Owner', 'Project', 'Final inspection','Inspections left'];
 	let sortOrders=['-plate.name','user.fullname','project.name','finalinspectiontime','inspectionsremaining'];
 	cellTemplates=[ '<a href="/plate/{{id}}">{{name}}</a>','<a href="/user/{{ownerid}}">{{ownername}}</a>',[Project.getLink,'name'],[ui.fieldToFriendlyDate,'finalinspectiontime'],'{{inspectionsremaining}}' ];
	let contentBefore='There may be other plates in the imager. These are the ones you have permission to see.';
	if(isAdmin){ contentBefore=""; }
	ts.tab({
		id:'contents',
		label:'Contents',
		url:'/api/imager/'+data['id']+'/plate?sortby=finalinspectiontime&pagesize='+data["platecapacity"],
		headers:headerTemplates,
		cellTemplates:cellTemplates,
        sortOrders:sortOrders,
		contentBefore:contentBefore
	});

	headerTemplates=['Inspection','Plate','Owner','Project'];
	cellTemplates=[ [ImagingSession.getLink,'imageddatetime'], '<a href="/plate/{{plateid}}">{{platename}}</a>', '{{ownername}}', [Project.getLink,'name'] ];
	if(isAdmin){
		cellTemplates=[ [ImagingSession.getLink,'imageddatetime'], '<a href="/plate/{{plateid}}">{{platename}}</a>', '<a href="/user/{{plateownerid}}">{{ownername}}</a>', [Project.getLink,'name'] ];
	}
	ts.tab({
		id:'inspections',
		label:'Latest inspections',
		url:'/api/imagingsession/imagerid/'+data['id']+'?sortby=imageddatetime&sortdescending=1',
		headers:headerTemplates,
		cellTemplates:cellTemplates
	});

    ts.filesTab();
    ts.notesTab();

	window.setTimeout(highlightExpiredPlates,500);
	
});

function highlightExpiredPlates(){
	let plateRows=document.getElementById("contents_body").querySelectorAll("tr");
	if(plateRows && 0<plateRows.length){
        const MS_PER_DAY = 1000 * 60 * 60 * 24;
        let now = new Date();
        let nowUTC = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
        plateRows.forEach(function(tr){
			if(!tr.rowData){ return; }
			if(0===1*tr.rowData["inspectionsremaining"]){
				tr.style.background="#fcc";
				tr.title="Plate has expired and should be removed from the imager";
			} else {
				let finalImaging=tr.rowData["finalinspectiontime"];
				if(finalImaging && finalImaging.match(/^\d\d\d\d-\d\d-\d\d/)){
					let finalUTC=Date.UTC(finalImaging.substring(0,4), (finalImaging.substr(5,2)-1), finalImaging.substr(8,2));
					let dayDiff=(nowUTC-finalUTC)/MS_PER_DAY;
					if(dayDiff>=7){ 
						tr.style.background="#ffc";
						tr.title="Plate has uncompleted final imaging more than one week old. The imager may have failed to mark it as expired. Plate should probably be removed from the imager.";
					}
				}
			}
		});
	}
	window.setTimeout(highlightExpiredPlates,2000); //to colour any more added by lazy load
}
</script>
<?php include realpath(__DIR__).'/../../core/_common/footer.php';