<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";
	import Select, { Option } from '@smui/select';
	import Button, { Label } from '@smui/button';
	import Dialog, { Title, Content, Actions } from '@smui/dialog';

    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.toUpperCase()});
		    
    		if(foundAsset.assigneeType === 'Student') {
			    foundAssignee = Students.findOne({_id: foundAsset.assigneeId});
		    }
    		else {
			    foundAssignee = Staff.findOne({_id: foundAsset.assigneeId});
		    }
	    }
    	else {
		    foundAssetType = undefined;
		    foundAssignee = undefined;
	    }
    }

	let conditions = ['New', 'Like New', 'Good', 'Okay', 'Damaged'];
	let condition = "New";
	let comment = "";
	let conditionDetails = "";
    
    const formatDate = (date) => {
        return date.toLocaleDateString('en-us', {weekday: 'long', year: 'numeric', month: 'short', day: 'numeric'});
    }
    const unassign = () => {
    	// if(confirm("Unassign Asset?")) {
    	// 	Meteor.call("assets.unassign", foundAsset.assetId);
	    // }
		condition = foundAsset.condition;
		conditionDetails = foundAsset.conditionDetails;

		openDialog();
    }

	let isDialogOpen = false;

	const openDialog = () => {
		// assetTypeDialogSelectedIndex = -1;
		isDialogOpen = true;
	}
	const dialogClosed = (e) => {
		switch (e.detail.action) {
			case 'unassign':
				if(foundAsset && foundAsset.assetId) {
					Meteor.call("assets.unassign", foundAsset.assetId, comment, condition, conditionDetails, (err, result) => {
						if(err) {
							console.error(err);
							//TODO: Display an error!
						}
						else {
							// TODO: Set focus to the asset ID field.

						}
					});
				}
				break;
			default:
			case 'cancel':
				break;
		}
	}
</script>

<div class="container">
	<Dialog bind:open={isDialogOpen} surface$style="width: 850px; max-width: calc(100vw - 32px);"
			on:SMUIDialog:closed={dialogClosed}>
		<Title id="large-scroll-title">Report Asset Condition</Title>
		<Content id="large-scroll-content">
			<Select bind:value={condition} label="Condition">
				{#each conditions as next}
					<Option value={next}>{next}</Option>
				{/each}
			</Select>
			<div style="grid-column: 1/span 1">
				<TextField type="text" style="width: 100%; margin-top: 1rem" bind:value={comment} label="Comment"></TextField>
			</div>
			<div style="grid-column: 1/span 1">
				<TextField textarea style="width: 100%; height: 20rem; margin-top: 1rem" helperLine$style="width: 100%" bind:value={conditionDetails} label="Condition Details">
				</TextField>
			</div>
		</Content>
		<Actions>
			<Button action="unassign" default>
				<Label>Ok</Label>
			</Button>
			<Button action="cancel">
				<Label>Cancel</Label>
			</Button>
		</Actions>
	</Dialog>

    <h1 style="display: block">Asset Assignments By Asset</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>
	    <div>Serial: {foundAsset.serial}</div>
		<div>Condition: {foundAsset.condition}</div>
		{#if foundAsset.conditionDetails}
			<div>Condition Details: {foundAsset.conditionDetails}</div>
		{/if}
	    {#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>

		    <Button variant="raised" touch on:click={unassign}>
			    <Label style="color: white">Unassign</Label>
		    </Button>
	    {/if}
    {/if}

<!--	<Dialog bind:open={showDialog} aria-labelledby="Confirm" aria-describedby="Unassign Confirmation">-->
<!--		&lt;!&ndash; Title cannot contain leading whitespace due to mdc-typography-baseline-top() &ndash;&gt;-->
<!--		<Title id="simple-title">Unassign Asset?</Title>-->
<!--		<Content id="simple-content"></Content>-->
<!--		<Actions>-->
<!--			<Button on:click={() => (clicked = 'No')}>-->
<!--				<Label>No</Label>-->
<!--			</Button>-->
<!--			<Button on:click={() => (clicked = 'Yes')}>-->
<!--				<Label>Yes</Label>-->
<!--			</Button>-->
<!--		</Actions>-->
<!--	</Dialog>-->
</div>

<style>

</style>