<?php

/** @var array $data The object we are going to view */
/** @noinspection PhpUnhandledExceptionInspection */

$hasConfig=true;
$pageTitle='Shipment: '.$data['name'];
$sharedProject=project::getByName(baseproject::SHARED);
if(!$sharedProject){
	throw new NotFoundException('Could not read shared project');
}
$sharedProjectId=$sharedProject['id'];
$canShip=shipment::canCreate();
include realpath(__DIR__).'/../../core/_common/header.php'; ?>
<!--suppress JSUnresolvedReference -->
    <script type="text/javascript">
<?php oidc::writeJavascriptVariables($data); ?>
//TODO Read-only if already shipped or non-admin/shipper/technician
let userCanShip=<?php echo $canShip ? 'true' : 'false'; ?>;

Crystal.KEEP="<?php echo diffractionrequest::KEEP_CRYSTAL; ?>";
Crystal.WASH="<?php echo diffractionrequest::WASH_CRYSTAL; ?>";

window.addEventListener('DOMContentLoaded',function(){

    document.getElementById("configbutton").addEventListener("click", Shipment.togglePageConfig);

    Shipment.getShipmentDestination();

	let grid=ui.grid();

	let ts=grid.tabSet({ id:"shiptabs", classes:'r1 c1 w3 h3' });
	let detailsTab=ts.tab({
		"label":"Shipment",
		"id":"shipmentdetails"
	});

	let frm=detailsTab.form({
		action:'/api/shipment/'+data.id,
		method:'patch',
		id:'shipmentdetails_form',
		readonly:!userCanShip || ""!==data.dateshipped
	});
	let frm2=detailsTab.form({
		action:'#',
		method:'get',
		id:'shipmentactions_form',
		classes:'noprint'
	});


	frm.hiddenField('projectid',<?php echo $sharedProjectId; ?>);
	frm.innerHTML+='<label><h3>Shipment details</h3></label>';
	frm.textField({ label:"Name", name:'name', value:data.name });
	frm.roleField({
		label:"Destination", 
		name:'shipmentdestinationid', 
		otherId:data["shipmentdestinationid"],
		otherName:data["shipmentdestinationname"],
		otherType:'shipmentdestination',
		labelField:'name',
		headers:['Name'],
		cellTemplates:['{{name}}']
	});
    if(data.beamlines.length){
        let lbl="Data collection beamline";
        let content=data.beamlines[0]["name"];
        if(1!==data.beamlines.length){
            lbl+="s";
            let names=[];
            data.beamlines.forEach(function (bl){
                names.push(bl.name);
            });
            content=names.join(", ");
        }
        frm.formField({ label:lbl, content:content })
    }
	frm.roleField({
		label:"Shipper", 
		name:'shipperid', 
		otherId:data["shipperid"],
		otherName:data["shippername"],
		otherType:'user',
		labelField:'fullname',
		headers:['Name'],
		cellTemplates:['{{fullname}}']
	});
	if(""!==data.dateshipped){
		if(""!==data.proposalname){
    		frm.textField({ label:"Proposal", name:'proposalname', value:data.proposalname, readOnly:true });
    		frm.textField({ label:"Session", name:'sessionname', value:data.sessionname, readOnly:true });
		}
		frm.dateField({ label:"Date shipped", name:'dateshipped', value:data.dateshipped, readonly:true });
	}
	if(""!==data.datereturned){
		frm.dateField({ label:"Date returned", name:'datereturned', value:data.datereturned, readonly: true });
	}


	if(userCanShip && ""===data.dateshipped){
    	frm2.innerHTML+='<label id="dewaraddlabel"><h3>Add a dewar</h3></label>';
    	frm2.textField({ label:"Scan a barcode", name:'addtoplevelbybarcode', placeholder:"Barcode" });
    	frm2.innerHTML+='<br/><br/><br/><label><h3>Send this shipment</h3></label>';
    	frm2.buttonField({ label:"Send shipment...", onclick:Shipment.send, id:"sendShipmentButton" });
    	frm2.onsubmit=function(){ Shipment.addDewarByBarcode(); return false; };
	}
    window.setTimeout(renderActionLinks	,100);

	if(""!==data["manifest"] && data["manifest"].rows){
		data["manifest"].rows.forEach(function(row){
			Shipment.renderDewar(row);
		});
	} else {
		Shipment.getAndRenderContainers();
	}	

	if(""!==data.dateshipped){
		if(""===data.datereturned){
    		//Shipped but not returned
    		Shipment.DataCollection.renderTab();
		} else if(userCanShip){
			//Shipped and returned
			Shipment.DewarReturn.renderTab();
		}
        Shipment.Results.renderTab();
	}

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

    ts.querySelectorAll(".tab").forEach(function (tab){
        tab.addEventListener("click",Shipment.toggleDewarTabIcons);
    })

	//TODO accept plates

    if("undefined"!==typeof actionOnReturn){
        switch (actionOnReturn){
            case "sendShipment":
                startSendShipmentAfterOidcAuth();
                break;
            case "getDatasets":
                alert("getDatasets is actionOnReturn - TODO");
                break;
        }
    }

});

function startSendShipmentAfterOidcAuth(){
    if(!window.shipmentDestination || ""===window.shipmentDestination["shipmenthandler"] || !window[shipmentDestination["shipmenthandler"]] || !document.querySelector(".containertab")){
        return window.setTimeout(startSendShipmentAfterOidcAuth, 100);
    }
    window.setTimeout(function(){ document.getElementById("sendShipmentButton").click() }, 100);
}

function renderActionLinks(){
	if(!window.shipmentDestination || ""===window.shipmentDestination["shipmenthandler"] || !window[shipmentDestination["shipmenthandler"]]){
		return window.setTimeout(renderActionLinks,250);
	}

    if(window[shipmentDestination["shipmenthandler"]]["CsvExport"] && ""===data.dateshipped){
        window[shipmentDestination["shipmenthandler"]]["CsvExport"].writeCsvExportButton(window.shipmentDestination);
        Shipment.showOrHideCsvExportButton();
    }

	if(""!==data.urlatremotefacility){
		let ff=document.getElementById("shipmentactions_form").formField({
			id:"remotelinklabel", 
			label:"&nbsp;", 
			content:'<a target="_blank" href="'+data.urlatremotefacility+'">Open shipment in new tab</a>' 
		});
        if(""===data.dateshipped){
            ff.insertAdjacentHTML('afterbegin','<h3>Placeholder shipment at '+window.shipmentDestination.name+'</h3><hr/>');
        } else {
            ff.insertAdjacentHTML('afterbegin','<h3>Your shipment at '+window.shipmentDestination.name+'</h3><hr/>');

        }
	}
	new AjaxUtils.Request('/api/shipment/'+data.id+'/file',{
		method:'get',
		onSuccess:function(transport){
			let files=transport.responseJSON.rows;
			files.forEach(function(file){
				if(file.filename==='shipment'+data.id+'manifest.pdf'){
					let ff2=document.getElementById("shipmentactions_form").formField({
						label:"&nbsp;", 
						content:'<a target="_blank" href="/api/file/'+file.id+'/'+file.filename+'">Open PDF in new tab</a>' 
					});
					ff2.insertAdjacentHTML('afterbegin','<h3>Printable shipment manifest</h3><hr/>');
				}
			});
			renderReturnLink();
            renderGetDatasetButton();
		},
		onFailure:function(){
			//meh
			renderReturnLink();
            renderGetDatasetButton();
        },
	});
    if(username.toLowerCase().endsWith("admin")){
        renderGetMxlimsJsonButton();
    }
}

function renderReturnLink(){
    if(userCanShip  && "" !==data.dateshipped && ""===data.datereturned){
        let ff=document.getElementById("shipmentactions_form").buttonField({ label:"Return shipment", onclick:Shipment.markReturned });
        ff.insertAdjacentHTML('afterbegin','<h3>Shipment return</h3><hr/>');
    }
}

function renderGetDatasetButton(){
    if(Shipment.hasDatasetRetrieval() && userCanShip && ""!==data.dateshipped){
        let ff=document.getElementById("shipmentactions_form").buttonField({ label:"Retrieve dataset metadata", onclick:Shipment.getCollectedDatasets });
        ff.insertAdjacentHTML('afterbegin','<h3>Dataset metadata</h3><hr/>');
    }
}

function renderGetMxlimsJsonButton(){
    let ff=document.getElementById("shipmentactions_form").buttonField({ label:"get MXLIMS JSON", onclick:function(){
            new AjaxUtils.request('/api/shipment/'+data.id,{
                method:'patch',
                parameters:{ "getMxlims":1 },
                onSuccess:function (xhr){
                    alert("Succeeded\n\n"+xhr.responseText);
                }, onFailure:function (xhr){
                    alert("Failed\n\n"+xhr.responseText);
                }
            });
        }
    });
    ff.insertAdjacentHTML('afterbegin','<h3>MXLIMS Shipment JSON</h3><hr/>');
}

</script>
<?php include realpath(__DIR__).'/../../core/_common/footer.php';

/*
 * Show spacegroup and best res on xtal summary bar, also num datasets, xtal star ratings
 * Dataset: star ratings, View button, best res, etc.
 *
 * Add star rating in data collection tab (re-score during DC)
 *
 * Rework crystal page datasets tab - use table with view buttons
 *
 * */