<script>
    import {Meteor} from "meteor/meteor";
    import {onMount} from "svelte";
    import TextField from '@smui/textfield';
    import {Staff} from "/imports/api/staff";
    import List, {Item, Graphic, Meta, Text, PrimaryText, SecondaryText} from '@smui/list';
    import Paper from '@smui/paper';
    import LayoutGrid, {Cell} from '@smui/layout-grid';
    import {Assets} from "/imports/api/assets";
    import {Students} from "/imports/api/students";
    import {AssetTypes} from "/imports/api/asset-types";

    onMount(async () => {
	    Meteor.subscribe('assets');
	    Meteor.subscribe('students');
	    Meteor.subscribe('staff');
	    Meteor.subscribe('assetTypes');
    });
    let searchText = "";
    let foundAsset;
    let selectedResult;
    let foundAssignee;
    let foundAssetType;

    $: {
        selectedResult = null;
	    
	    if(searchText) {
		    foundAsset = Assets.findOne({assetId: searchText});
	    }
	    else {
		    foundAsset = undefined;
	    }
    }
    
    $: {
    	if(foundAsset) {
		    foundAssetType = AssetTypes.findOne({_id: foundAsset.assetTypeId});
		    
    		if(foundAsset.assigneeType === 'Student') {
			    foundAssignee = Students.findOne({_id: foundAsset.assigneeId});
		    }
    		else {
			    foundAssignee = Staff.findOne({_id: foundAsset.assigneeId});
		    }
	    }
    	else {
		    foundAssetType = undefined;
		    foundAssignee = undefined;
	    }
    }
    
    const formatDate = (date) => {
        return date.toLocaleDateString('en-us', {weekday: 'long', year: 'numeric', month: 'short', day: 'numeric'});
    }
</script>

<div class="container">
    <h1 style="display: block">Asset Assignments</h1>

    <Paper>
        <LayoutGrid>
            <Cell span="{6}">
                <TextField type="text" bind:value={searchText} label="Asset ID"></TextField>
            </Cell>
        </LayoutGrid>
    </Paper>

    {#if foundAsset}
	    <div>Asset ID: {foundAsset.assetId}</div>
	    {#if foundAssetType}
		    <div>{foundAssetType.name}</div>
	    {/if}
	    {#if foundAssignee}
		    <div>Assigned on: {formatDate(foundAsset.assignmentDate)}</div>
	        <div>Assigned to: {foundAssignee.firstName} {foundAssignee.lastName}
		        {#if foundAssignee.grade} ~ {foundAssignee.grade} {/if}({foundAssignee.email})</div>
	    {/if}
    {/if}
</div>

<style>

</style>