<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';

	onMount(async () => {
		Meteor.subscribe('sites');
	});

	// Load the sites (reactive).
	let sites = Sites.find({});
	let selectedSiteId;

	let students;
	let studentCount = 0;
	$: {
		if(selectedSiteId) {
			Meteor.subscribe('students', selectedSiteId);
			students = Students.find({siteId: selectedSiteId});
		}
	}
	$: {
		if(students) {
			studentCount = $students.length;
		}
		else {
			studentCount = 0;
		}
	}
	
	let uploadType = 'CSV'

	const uploadStudents = () => {
		// console.log(files);
		// console.log(selectedSite);
		// console.log(selectedSite._id);
		if(files && files.length) {
			let file = files[0];
			let reader = new FileReader();
			reader.onload = (e) => {
				// console.log("Sending Data");
				// console.log(selectedSite._id);
				// console.log(reader.result);
				Meteor.call('students.loadCsv', reader.result, uploadType, selectedSiteId);
			}
			reader.readAsText(file, "UTF-8");
		}
	}
	let files;

	const studentColumns = [
		{
			key: "email",
			title: "Email",
			value: v => v.email,
			minWidth: 100,
			weight: 1,
			cls: "email",
		}, {
			key: "firstName",
			title: "First Name",
			value: v => v.firstName,
			minWidth: 100,
			weight: 1,
			cls: "firstName",
		}, {
			key: "lastName",
			title: "Last Name",
			value: v => v.lastName,
			minWidth: 100,
			weight: 1,
			cls: "lastName",
		}, {
			key: "grade",
			title: "Grade",
			value: v => v.grade,
			minWidth: 100,
			weight: 1,
			cls: "grade",
		},
	];
	const studentsActions = {
		title: "Actions",
		headerWidgets: [
			{icon: "add_box", action: () => {editedStudent.set({});}, tooltip: "Add a student."}
		],
		rowWidgets: [
			{icon: "add_circle", action: (v) => {editedStudent.set(v)}},
			{icon: "delete", action: (v) => {deleteStudent(v)}}
		],
	};
	let siteSelectComponent;
	let editedStudent = writable(null);
	const onStudentSelection = (e) => {
	}
	let dirtyStudent;
	// Copy the edited value when ever it changes, set some defaults for a new value object (to make the view happy).
	editedStudent.subscribe(v => {dirtyStudent = Object.assign({email: "", firstName: "", lastName: "", grade: ""}, v)});
	const deleteStudent = student => {
		//TODO:
	};
	const applyStudentChanges = () => {
		if(dirtyStudent._id)
			Meteor.call("students.update", dirtyStudent);
		else
			Meteor.call("students.add", dirtyStudent);
		editedStudent.set(null);
		dirtyStudent = null;
	}
	const rejectStudentChanges = () => {
		editedStudent.set(null);
	}
	let openExportHelpDialog = false;
	const clickOpenExportHelpDialog = () => {
		openExportHelpDialog = true;
	}
</script>

<div class="container">
	<Select bind:value={selectedSiteId} label="Site" bind:this={siteSelectComponent}>
		{#each $sites as site}
			<Option value={site._id}>{site.name}</Option>
		{/each}
	</Select>
	<h2>Site Students ({studentCount})</h2>
	<form on:submit|preventDefault={uploadStudents}>
		<input style="display: inline-block" type="file" multiple="false" accept="text/*" bind:files={files}/>
		<select bind:value={uploadType}>
			<option value="CSV">Comma Separated Value (CSV)</option>
			<option value="Aeries Text Report">Aeries Text Report (TXT)</option>
		</select>
		<input disabled="{!selectedSiteId}" type="submit" value="Upload"/>
		<input type="button" value="?" on:click={clickOpenExportHelpDialog}/>
	</form>
	<GridTable bind:rows={students} columns="{studentColumns}" actions="{studentsActions}" rowKey="{(v) => {return v._id}}" bind:edited="{editedStudent}" on:selection={onStudentSelection}>
		{#if dirtyStudent}
			<div class="editorContainer">
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStudent.email} label="Email">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStudent.firstName} label="First Name">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStudent.lastName} label="Last Name">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStudent.grade} label="Grade">
					</TextField>
				</div>

				<button type="button" style="grid-column: 2/span 1;" class="button accept-button material-icons material-symbols-outlined" on:click={applyStudentChanges}>
					check
				</button>
				<button type="button" style="grid-column: 3/span 1;" class="button reject-button material-icons material-symbols-outlined" on:click={rejectStudentChanges}>
					close
				</button>
			</div>
		{/if}
	</GridTable>
	
	<Dialog bind:open={openExportHelpDialog} aria-labelledby="exportHelpTitle" aria-describedby="exportHelpContent" surface$style="width: 800px; max-width: calc(100vw - 32px);">
		<Title id="exportHelpTitle">Exporting Student Data</Title>
		<Content id="exportHelpContent">
			<h3>Aeries</h3>
			<p>For the Aeries system, log into your Aeries web interface and navigate to the query page.  Enter the following query:</p>
			<h4>Pre-Rollover</h4>
			<pre style="font-size: 0.7rem"><code>LIST STU STU.ID STU.SEM STU.FN STU.LN STU.NG BY STU.ID STU.NG STU.SEM IF STU.NG &gt;= 7 AND NG &lt;= 12 AND STU.NS = 5</code></pre>
			<h4>Post-Rollover</h4>
			<pre style="font-size: 0.7rem"><code>LIST STU STU.ID STU.SEM STU.FN STU.LN STU.NG BY STU.ID STU.NG STU.SEM IF STU.NG &gt;= 7 AND GR &lt;= 12 AND STU.SC = 5</code></pre>
			<p>Run the query and validate that all students have an email address and a student ID.  You likely also want to check that the student `next grade (NG)` field is set correctly for the students (pre-rollover).</p>
			<p>You have two options for export.  You can:</p>
			<ol class="help">
				<li class="help">Click the `Report` button to generate a TXT formatted report.  Use Single Spacing, Automatic Orientation and no page breaks.  The generated text is CSV but with a repeating collection of headers for each page.  The headers will be ignored.</li>
				<li class="help">Click the `Excel` button to generate an excel spreadsheet of the results.  Open this with any spreadsheet software (Excel, LibreOffice Calc, or Google Sheets) and save as CSV.  The first line in the CSV file is assumed to be a header and will be ignored.</li>
			</ol>
			<p>Now upload the generated CSV file (or text file).</p>
		</Content>
		<Actions>
			<Button action="accept">
				<Label>Done</Label>
			</Button>
		</Actions>
	</Dialog>
</div>

<style>
    form {
        margin: 0;
    }
    ol.help {
	    list-style-type: decimal;
	    margin-top: 0.2rem;
	    margin-bottom: 0.2rem;
    }
    li.help {
        list-style: inherit;
        padding-top: 0.2rem;
        padding-bottom: 0.2rem;
    }
    .editorContainer {
        display: grid;
        grid-template-columns: minmax(10px, 1fr) minmax(3rem, 3rem) minmax(3rem, 3rem);
    }
    .accept-button, .reject-button {
        font-size: .8rem;
        padding: .6rem;
        margin: auto;
        color: white;
        border-radius: 50%;
        border: 0;
        font-weight: 800;
        alignment: center;
        cursor: pointer;
    }
    .accept-button {
        background-color: rgba(61, 148, 61, 0.91);
    }
    .reject-button {
        background-color: rgba(176, 64, 64, 0.61);
    }
    .accept-button:hover {
        background-color: rgb(61, 148, 61);
    }
    .reject-button:hover {
        background-color: rgb(176, 64, 64);
    }
</style>
