<?php
/** @var array $data The object we are going to view */
/** @noinspection PhpUnhandledExceptionInspection */
$sharedProject=project::getByName(baseproject::SHARED);
if(!$sharedProject){
	throw new NotFoundException('Could not read shared project');
}
$sharedProjectId=$sharedProject['id'];
$pageTitle='Shipment destination: '.$data['name'];
$shipmentHandlers=shipmentdestination::getHandlerScriptNames();
include realpath(__DIR__).'/../../core/_common/header.php'; ?>
<script type="text/javascript">

window.addEventListener('DOMContentLoaded',function(){
    const isManaged=1*data['ismanaged'];
    const grid = ui.grid();
    const detailsBox = grid.box({
        classes: 'r1 c1 h3 w1',
        title: 'Details'
    });

    if(1===1*data['ishome']){
        ui.infoMessageBar('This is the home lab.', detailsBox);
    }

    if(1===1*data['ismanaged']){
        ui.infoMessageBar('This destination is managed by IceBear.', detailsBox);
    }


    const frm = detailsBox.form({
        action: '/api/shipmentdestination/' + data['id'],
        method: 'post',
        'readonly':!isAdmin && !isTechnician
    });
    frm.hiddenField('projectid',<?php echo $sharedProjectId; ?>);

    frm.checkbox({
       "label":"Available for shipments",
       "name":"isavailable",
       "value":data["isavailable"]
    });

	frm.textField({ label:"Name", name:'name', readonly:isManaged });

	frm.dropdown({ label:"Shipment handler", name:"shipmenthandler", readonly:isManaged,
		options:[
			<?php 
			     $parts=array();
			     foreach($shipmentHandlers as $h){
			         $parts[]='{ "value":"'.$h.'","label":"'.$h.'" }';
			     } 
			     echo implode(', ', $parts);
			?>
		],
		value:data["shipmenthandler"]
	});
	frm.textField({ label:"Base URI", name:'baseuri', readonly:isManaged });

    let ts=grid.tabSet({ classes:'r1 c2 w2 h3' });
	ts.tab({
		'label':'Shipments',
		'url':'/api/shipmentdestination/'+data.id+'/shipment',
		'sortby':'dateshipped',
		'headers':['Name'],
		'cellTemplates':['<a href="/shipment/{{id}}">{{name}}</a>']
	});

    ts.tab({
        'id':'beamlines',
        'label':'Beamlines',
        'content':'Loading...',
    });
    getBeamlines();

    ts.mapTab({
        "geofence": data['geofence'],
        "readonly": isManaged || !(isAdmin || isTechnician)
    });
	ts.filesTab();
	ts.notesTab();

		
});

function getBeamlines(){
    new AjaxUtils.Request('/api/shipmentdestination/'+data.id+'/beamline?sortby=name',{
        method:"get",
        onFailure:beamlinesTable,
        onSuccess:beamlinesTable,
    });
}

function beamlinesTable(transport){
    if(transport.responseJSON){ transport=transport.responseJSON; }
    let beamlines=[];
    if(transport['rows']) {
        let control="";
        if(canEdit){
            control='<img s'+'rc="/images/icons/btn_no.gif" alt="Delete" title="Delete this beamline" onclick="deleteBeamline(this)"/>';
        }
        beamlines=transport['rows'];
        beamlines.forEach(function(bl){
           bl["control"]=control;
        });
    }
    if(canEdit){
        beamlines.push({
            'name':'<input type="text" name="name" placeholder="Name"/>',
            'detectormanufacturer':'<input type="text" name="detectormanufacturer" placeholder="Manufacturer"/>',
            'detectormodel':'<input type="text" name="detectormodel" placeholder="Model"/>',
            'detectortype':'<input type="text" name="detectortype" placeholder="Type"/>',
            'control':'<input type="button" value="Add" onclick="addBeamline(this)"/>',
        });
    }
    ui.table({
            'headers':['Name','Detector manufacturer and model','Detector type',''],
            'cellTemplates':['{{name}}', '{{detectormanufacturer}} {{detectormodel}}', '{{detectortype}}', '{{control}}'],
        },
        beamlines,
        document.getElementById("beamlines_body")
    );
}

function addBeamline(btn){
    let tr=btn.closest("tr");
    tr.classList.add("updating");
    let parameters={
        csrfToken:csrfToken,
        projectid:<?php echo $sharedProjectId; ?>,
        shipmentdestinationid:data.id
    };
    tr.querySelectorAll('input[type=text]').forEach(function(inp){
       parameters[inp.name]=inp.value;
    });
    new AjaxUtils.Request("/api/beamline",{
        method:'post',
        parameters:parameters,
        onSuccess:getBeamlines,
        onFailure:AjaxUtils.checkResponse
    });
}

function deleteBeamline(btn){
    if(!confirm("Really remove this beamline?")){ return false; }
    let tr=btn.closest("tr");
    tr.classList.add("updating");
    let parameters={
        csrfToken:csrfToken
    };
    tr.querySelectorAll('input[type=text]').forEach(function(inp){
        parameters[inp.name]=inp.value;
    });
    new AjaxUtils.Request("/api/beamline/"+tr["rowData"]["id"],{
        method:'delete',
        parameters:parameters,
        onSuccess:getBeamlines,
        onFailure:AjaxUtils.checkResponse
    });
}

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