<script>
    import {Meteor} from "meteor/meteor";
    import {onMount} from "svelte";
    import {Sites} from "../../api/sites";
    import TextField from '@smui/textfield';
    import {Students} from "../../api/students";
    import Select, { Option } from '@smui/select';
    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 = ['Staff', 'All Grades'];
    onMount(async () => {
        Meteor.subscribe('sites');
        Meteor.call('students.getPossibleGrades', (err, result) => {
            if(err) console.log(err);
            else {
                grades = ['Staff', 'All Grades', ...result];
            }
        });
    });
    // Load the sites (reactive).
    let sites = Sites.find({});
    let selectedSiteId;
    let categories = ['Asset ID', 'Email', 'First Name', 'Last Name'];
    let selectedCategory = 'Email';
    let selectedGrade = 'All Grades';
    let searchText = "";
    let searchResults;
    let selectedResult;

    $: {
    	console.log("Site ID")
	    console.log(selectedSiteId)
        if(selectedSiteId) {
            Meteor.subscribe('students', selectedSiteId);
            Meteor.subscribe('staff', selectedSiteId);
        }
    }

    $: {
        selectedResult = null;
        console.log("Starting search")

        // Require at least two characters in the search field before we start filtering.
        if(selectedSiteId && selectedGrade && selectedCategory) {
            let query = {};
            let queryType = (selectedGrade === "Staff") ? 1 : 0;

            if(searchText && searchText.length > 0) {
	            if (selectedCategory === 'Email') {
		            query.email = {$regex: searchText, $options: 'i'};
	            } else if( selectedCategory === 'Asset ID') {
                    //Do not do anything yet...
                } else if (selectedCategory === 'First Name') {
		            query.firstName = {$regex: searchText, $options: 'i'};
	            } else {
		            query.lastName = {$regex: searchText, $options: 'i'};
	            }
            }

            if(selectedCategory === 'Asset ID') {
                Meteor.call('AssetAssignments.getOne', searchText, (err, result) => {
                   if(err) {
                       console.error(err);
                   }
                   else {
                       if(result && result.assigneeType && result.assigneeId) {
                           if (result.assigneeType === 'Staff') {
                                query._id = result.assigneeId;
                                queryType = 1;
                           } else if (result.assigneeType === 'Student') {
                               query._id = result.assigneeId;
                               queryType = 0;
                           } else {
                               console.error("Invalid AssigneeType");
                           }
                       }
                       else {
                           console.error('Invalid result from AssetAssignments.getOne');
                       }
                   }
                });
            }

            if(queryType === 1) {
                searchResults = Staff.find(query);
            }
            else {
                if(selectedGrade !== 'All Grades') {
                    query.grade = selectedGrade;
                }

                // console.log("Searching")
	            // console.log(query)
                searchResults = Students.find(query);
            }
        }
        else {
            searchResults = undefined;
        }
    }
</script>

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

    <Paper>
        <LayoutGrid>
            <Cell span="{6}">
                <Select bind:value={selectedSiteId} label="Site">
                    {#each $sites as site}
                        <Option value={site._id}>{site.name}</Option>
                    {/each}
                </Select>
            </Cell>
            <Cell span="{6}">
                <Select bind:value={selectedGrade} label="Grade">
                    {#each grades as grade}
                        <Option value={grade}>{grade}</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}">
                <TextField type="text" bind:value={searchText} label="Search"></TextField>
            </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>
	    {#if searchResults}
        {#each $searchResults as result}
            <Item selected={selectedResult === result}>
                <Text>
                    <PrimaryText>{result.firstName} {result.lastName}</PrimaryText>
                    <SecondaryText>{result.email} {result.grade ? '(' + result.grade + ')' : ""}</SecondaryText>
                </Text>
            </Item>
        {/each}
	    {/if}
    </List>
</div>

<style>

</style>