<?php
/** @var array $data */
$pageTitle='Plate: '.$data['name'];
$breadcrumbs=array(
		array('url'=>'/project/'.$data['projectid'], 'icon'=>'project', 'help'=>'Go to this plate\'s project')
);
/** @var array $data The object we are going to view */
/** @noinspection PhpUnhandledExceptionInspection */
$qItem=platereimportqueue::getByPlateId($data['id']);
include realpath(__DIR__).'/../../core/_common/header.php'; ?>
<script type="text/javascript">
canEdit=<?php /** @noinspection PhpUnhandledExceptionInspection */ echo plate::canUpdate($data['id'])?'true':'false'; ?>;
if(!canEdit && 1*data["ownerid"]===1*userId){ canEdit=true; }
let isDestroyed=(""!==data["datedestroyed"]);
let canCreateInspections=canEdit && !isDestroyed && <?php echo (1==config::get('imaging_allowmanual')) ? 'true' : 'false'; ?>;
let canReimport=<?php echo (1==config::get('reimport_enabled') && (session::isAdmin() || session::getUserId()==$data['ownerid'])) ? 'true' : 'false'; ?>;
let queueItem= <?php echo json_encode($qItem); ?>;
let isQueuedForReimport=<?php echo ($qItem? 'true;' : 'false;'); ?>;
const DEFAULT_PROJECT_ID=<?php echo project::getDefaultProjectId();?>;

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

    //Append barcode to URL
    let loc=window.location.href+"";
    if(-1===loc.indexOf(data['name'])){
        window.history.replaceState({}, '', loc+"#barcode:"+data["name"]);
    }

	Plate.getManualImagers();
	Plate.getPlateType();
	Plate.getWellDrops();
	Plate.getConstructs();
	
	ui.grid();

    let boxHeight=canEdit? 2 : 3;
	let details=grid.box({
		classes:'r1 c1 h'+boxHeight+' w1',
		title:'Details'
	});

    ui.archivedProjectMessageBar(details);

	let df=details.form({
        readonly:!canEdit,
		action:'/api/plate/'+data["id"],
		method:'patch'
	});
	df.textField({
		label:'Barcode',
		value:data["name"],
		readonly:true
	});
	df.textField({
		label:'Description',
		name:'description',
		value:data["description"],
		readonly:!canEdit
	});
	df.formField({ label:"Plate type"}).innerHTML+='<a href="/platetype/'+data["platetypeid"]+'">'+data["platetypename"]+'</a>';
	let projectField=df.formField({ label:"Project", id:'project' });
    if(1*DEFAULT_PROJECT_ID===1*data['projectid']){
        projectField.innerHTML+='<img alt="warning" title="Plate is in default project" style="vertical-align:top" src="/images/icons/'+skin["bodyIconTheme"]+'icons/warning.png">&nbsp;'+data["projectname"]+'&nbsp;&nbsp;<input type="button" value="Change..."/>';
        projectField.querySelector("input").addEventListener("click",function (){
            let mb=document.getElementById("proteins_body").querySelector(".msgbar");
            mb.style.opacity="0";
            document.getElementById("proteins").click();
            fadeInMessageBar(mb);
        });
    } else {
        projectField.innerHTML+='<a href="/project/'+data["projectid"]+'">'+data["projectname"]+'</a>';
    }
	df.roleField({
		label:"Owner",
		name:'ownerid', 
		otherId:data["ownerid"],
		otherName:data["ownername"],
		otherType:'user',
		labelField:'fullname',
		headers:['Name'],
		cellTemplates:['{{fullname}}']
	});

	//TODO better handling of long text
    if(df.querySelector("#description")){
        df.querySelector("#description").style.width="70%";
    }

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

    let contentBefore = null;
    let sortOrders = ['-imageddatetime', '', ''];
    let headers = ['Inspection', 'Temperature', 'Imager'];
    let cellTemplates = [
        [Plate.writeInspectionLink, 'imageddatetime'],
        '{{temperature}}C',
        '<a href="/imager/{{imagerid}}" title="{{imagername}}">{{imagerfriendlyname}}</a>'
    ];

    let newInspectionButton='<input type="button" style="float:none" value="Create new manual inspection for this plate..." onclick="Plate.beginCreateInspection()" />';

	if(canCreateInspections){
		contentBefore=newInspectionButton;
		headers.push(' ');
		sortOrders.push('');
		cellTemplates.push([
			function(){
				return '<input type="button" value="Edit..." onclick="Plate.beginEditInspection(this)" />';
			},
			'manualimaging'
		]);
	}
	
	ts.tab({
		id:'inspections',
		label:'Inspections',
		url:'/api/plate/'+data['id']+'/imagingsession',
		headers:headers,
		cellTemplates:cellTemplates,
		sortOrders:sortOrders,
		sortBy:"imageddatetime",
		sortDescending:true,
		contentBefore:contentBefore,
		failureHandler:function(){
			let content='No inspections on this plate';
			if(canCreateInspections){
				content+='<br/><br/>'+newInspectionButton;
			} else {
			    content='&nbsp;';
            }
			document.getElementById("inspections_body").innerHTML=content;
		}
	});

	ts.tab({
		id:'crystals',
		label:'Crystals',
		url:'/api/plate/'+data['id']+'/crystal',
        contentBefore:getFishLink(),
		headers:['Rating','Image','Drop and number'],
		cellTemplates:[ [ui.starRatingCellContents,'starrating'], [Crystal.getThumbnailLink,'id'], [Crystal.getTextLink,'id'] ],
        sortOrders:["-starrating","","id"]
	});
    insertFishLinkIfNoCrystals();

	ts.tab({
		id:'proteins',
		label:'Protein',
		renderer:Plate.renderProteinTab,
	});

	ts.tab({
		id:'screens',
		label:'Screen',
		renderer:Plate.renderScreenTab,
	});

    let dc = ts.tab({
        id: 'drops',
        label: 'Drop conditions',
        renderer: Plate.renderDropConditionsTab,
    });
    dc.onclick=Plate.renderDropConditionsTab; //Force render onclick because width doesn't take.

    /* TODO seeding tab - only mockup in renderSeedingTab
    let s=ts.tab({
       "id":"seeding",
       "label":"Seeding",
       "renderer":Plate.renderSeedingTab
    });
    s.onclick=Plate.renderSeedingTab;
*/

    ts.filesTab(data["screenid"]);
    ts.notesTab();

    if(canEdit) {
        let actions = grid.box({
            classes: 'r3 c1 h1 w1',
            title: 'Actions'
        });
        let af = actions.form({
            action: '/api/plate/' + data["id"],
            method: 'get'
        });

        let destroyedField;
        if (isDestroyed) {
            destroyedField = af.formField({label: "Plate has been destroyed"});
            if (canEdit) {
                destroyedField.innerHTML += '<input type="button" value="Undo" onclick="updateDestroyed(this)" />';
            }
        } else if (canEdit) {
            destroyedField = af.formField({label: "Mark plate as destroyed:"});
            destroyedField.innerHTML += '<input type="button" value="Destroy plate" onclick="updateDestroyed(this)" />';
        }

        if (!isDestroyed && canReimport) {
            let reimportField;
            if (isQueuedForReimport) {
                reimportField = af.formField({label: "Plate is queued for re-import"});
                reimportField.innerHTML += '<input type="button" id="reimport" value="Cancel" onclick="cancelReimport()" />';
            } else {
                reimportField = af.formField({label: "Queue plate for re-import:"});
                reimportField.innerHTML += '<input type="button" id="reimport" value="Queue" onclick="queueForReimport()" />';
            }
        }
    }
});

function fadeInMessageBar(messageBar){
    let o=messageBar.style.opacity*1;
    if(o<1){
        messageBar.style.opacity=(o+0.05)+"";
        window.setTimeout(fadeInMessageBar,50,messageBar);
    }
}

function insertFishLinkIfNoCrystals(){
    let tb=document.getElementById("crystals_body");
    if("Loading..."===tb.innerHTML){
        window.setTimeout(insertFishLinkIfNoCrystals, 250);
        return;
    }
    if("None found"===tb.innerHTML){
        tb.innerHTML+='<p>'+getFishLink()+'</p>';
    }
}

function getFishLink(){
    if(!canEdit){ return ""; } //can't update the plate, so can't fish crystals from it
	if(isDestroyed){ return ""; }
	if(!data["projectname"] || 'Default Project'===data["projectname"]){ return ""; }
	return '<a class="nosmall" href="/containercontent/create?barcodes='+data["name"]+'">Fish crystals from this plate...</a>';
}

//TODO move to client.js::Plate, accept plate ID and date. If no date supplied (NOT empty), undestroy
function updateDestroyed(btn){
	if(!Plate.setIsDestroyed(data["id"], !isDestroyed)){
		return false;
	}
    btn.closest("label").classList.add("updating");
}

function cancelReimport(){
	document.getElementById("reimport").closest("label").classList.add("updating");
	new AjaxUtils.Request('/api/platereimportqueue/'+queueItem.id,{
		method:'delete',
		parameters:{
			csrfToken:csrfToken
		},
		onSuccess:afterImportChange,
		onFailure:AjaxUtils.checkResponse
	});
}
function queueForReimport(){
    document.getElementById("reimport").closest("label").classList.add("updating");
	new AjaxUtils.Request('/api/platereimportqueue/',{
		method:'post',
		parameters:{
			csrfToken:csrfToken,
			plateid:data["id"]
		},
		onSuccess:afterImportChange,
		onFailure:AjaxUtils.checkResponse
	});
}
function afterImportChange(){
	ui.forceReload();
}

</script>

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