<script>
	import {Meteor} from "meteor/meteor";
	import {onMount} from "svelte";
	import {Sites} from "../../api/sites";
	import GridTable from "./../GridTable.svelte";
	import {writable} from "svelte/store";
	import TextField from '@smui/textfield';
	import HelperText from '@smui/textfield/helper-text';
	import {Students} from "../../api/students";
	import Select, { Option } from '@smui/select';
	import Dialog, { Title, Content, Actions } from '@smui/dialog';
	import Button, { Label } from '@smui/button';
	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';

	let grades = ['All'];
	onMount(async () => {
		Meteor.subscribe('sites');
		Meteor.call('students.getPossibleGrades', (err, result) => {
			if(err) console.log(err);
			else {
				grades = ['All', ...result];
			}
		});
	});
	// Load the sites (reactive).
	let sites = Sites.find({});
	let selectedSiteId;
	let assignees;
	let siteSelectComponent;
	let categories = ['Student', 'Staff'];
	let selectedCategory = 'Student';
	let sorts = [{column: 'firstName', name: 'First Name'}, {column: 'lastName', name: 'Last Name'}, {column: 'email', name: 'Email'}];
	let selectedSort = 'firstName'
	let selectedGrade = 'All';
	let selectedAssignee;
	let assetId = "";
	let assetIdWidget;

	$: {
		if(selectedSiteId) {
			if(selectedCategory === 'Student') {
				Meteor.subscribe('students', selectedSiteId);
				let filter = {siteId: selectedSiteId};
				
				if(selectedGrade && selectedGrade !== 'All') filter.grade = selectedGrade;
				assignees = Students.find(filter, {sort: [selectedSort]});
			}
			else if(selectedCategory === 'Staff') {
				Meteor.subscribe('staff', selectedSiteId);
				assignees = Staff.find({siteId: selectedSiteId}, {sort: [selectedSort]});
			}
		}
	}

	const createAssignment = () => {
		if(assetId && assetId.length && selectedAssignee) {
			Meteor.call("assets.assign", assetId, selectedCategory === 'Student' ? "Student" : "Staff", selectedAssignee._id, (err, result) => {
				if(err) {
					console.error(err);
					//TODO: Display an error!
				}
				else {
					// TODO: Set focus to the asset ID field.
					assetId = "";
				}
			});
		}
	}
</script>

<div class="container">
	<h1 style="display: block">Assign Assets</h1>

	<Paper>
		<LayoutGrid>
			<Cell span="{6}">
				<Select bind:value={selectedSiteId} label="Site" bind:this={siteSelectComponent}>
					{#each $sites as site}
						<Option value={site._id}>{site.name}</Option>
					{/each}
				</Select>
			</Cell>
			<Cell span="{6}">
				<Select bind:value={selectedCategory} label="Category">
					{#each categories as category}
						<Option value={category}>{category}</Option>
					{/each}
				</Select>
			</Cell>
			<Cell span="{6}">
				{#if (selectedCategory === 'Student')}
					<Select bind:value={selectedGrade} label="Grade">
						{#each grades as grade}
							<Option value={grade}>{grade}</Option>
						{/each}
					</Select>
				{/if}
			</Cell>
			<Cell span="{6}">
				<Select bind:value={selectedSort} label="Sort">
					{#each sorts as sort}
						<Option value={sort.column}>{sort.name}</Option>
					{/each}
				</Select>
			</Cell>
		</LayoutGrid>
	</Paper>

	<div style="width: 100%; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; align-items: flex-end; align-content: stretch; column-gap: 2rem;">
		<TextField bind:this={assetIdWidget} style="flex-grow: 999;" type="text" bind:value={assetId} label="Asset ID">

		</TextField>
		<Button variant="raised" color="secondary" on:click={createAssignment} disabled={!assetId || assetId.length === 0 || !selectedAssignee}>
			<Label style="color: white">Create</Label>
		</Button>
	</div>
	<List twoLine singleSelection style="max-height: 60%">
		{#if $assignees}
			{#each $assignees as assignee}
				<Item on:SMUI:action={() => (selectedAssignee = assignee)} selected={selectedAssignee === assignee}>
					<Text>
						<PrimaryText>{assignee.firstName} {assignee.lastName}</PrimaryText>
						<SecondaryText>{assignee.email} {assignee.grade ? '(' + assignee.grade + ')' : ""}</SecondaryText>
					</Text>
				</Item>
			{/each}
		{/if}
	</List>
</div>

<style>
	
</style>