<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 {Staff} from "../../api/staff";
	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 staff = null;
	let staffCount = 0;
	$: {
		if(selectedSiteId) {
			Meteor.subscribe('staff', selectedSiteId);
			staff = Staff.find({siteId: selectedSiteId});
		}
	}
	$: {
		if(staff) {
			staffCount = $staff.length;
		}
		else {
			staffCount = 0;
		}
	}

	let uploadType = 'CSV'

	const uploadStaff = () => {
		// 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('staff.loadCsv', reader.result, uploadType, selectedSiteId);
			}
			reader.readAsText(file, "UTF-8");
		}
	}
	let files;

	const staffColumns = [
		{
			key: "id",
			title: "ID",
			value: v => v.id,
			minWidth: 100,
			weight: 1,
			cls: "id",
		}, {
			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",
		},
	];
	const staffActions = {
		title: "Actions",
		headerWidgets: [
			{icon: "add_box", action: () => {editedStaff.set({});}, tooltip: "Add a staff member."}
		],
		rowWidgets: [
			{icon: "add_circle", action: (v) => {editedStaff.set(v)}},
			{icon: "delete", action: (v) => {deleteStaff(v)}}
		],
	};
	let editedStaff = writable(null);
	let siteSelectComponent;
	const onStaffSelection = (e) => {

	}
	let dirtyStaff;
	// Copy the edited value when ever it changes, set some defaults for a new value object (to make the view happy).
	editedStaff.subscribe(v => {dirtyStaff = Object.assign({id: "", email: "", firstName: "", lastName: "", siteId: selectedSiteId}, v)});
	const deleteStaff = staff => {
		//TODO: We must first ensure we have no assets assigned to the staff member.
	};
	const applyStaffChanges = () => {
		if(dirtyStaff._id) {
			Meteor.call("staff.update", dirtyStaff._id, dirtyStaff.id, dirtyStaff.firstName, dirtyStaff.lastName, dirtyStaff.email, dirtyStaff.siteId);
		}
		else {
			Meteor.call("staff.add", dirtyStaff.id, dirtyStaff.firstName, dirtyStaff.lastName, dirtyStaff.email, dirtyStaff.siteId);
		}
		editedStaff.set(null);
		dirtyStaff = null;
	}
	const rejectStaffChanges = () => {
		editedStaff.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 Staff ({staffCount})</h2>
	<form on:submit|preventDefault={uploadStaff}>
		<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={staff} columns="{staffColumns}" actions="{staffActions}" rowKey="{(v) => {return v._id}}" bind:edited="{editedStaff}" on:selection={onStaffSelection}>
		{#if dirtyStaff}
			<div class="editorContainer">
				<div style="grid-column: 1/span 1">
					<TextField type="number" style="width: 100%" bind:value={dirtyStaff.id} label="ID">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStaff.email} label="Email">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStaff.firstName} label="First Name">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<TextField type="text" style="width: 100%" bind:value={dirtyStaff.lastName} label="Last Name">
					</TextField>
				</div>
				<div style="grid-column: 1/span 1">
					<Select bind:value={dirtyStaff.siteId} label="Site">
						{#each $sites as site}
							<Option value={site._id}>{site.name}</Option>
						{/each}
					</Select>
				</div>

				<button type="button" style="grid-column: 2/span 1;" class="button accept-button material-icons material-symbols-outlined" on:click={applyStaffChanges}>
					check
				</button>
				<button type="button" style="grid-column: 3/span 1;" class="button reject-button material-icons material-symbols-outlined" on:click={rejectStaffChanges}>
					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 Staff 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 (change PSC = 5 to your school's number):</p>
			<pre style="font-size: 0.7rem"><code>LIST STF ID EM FN LN BY FN IF PSC = 5 AND TG # I</code></pre>
			<p>Run the query and validate that all staff have an email address and a staff ID.  The `TG # I` hides staff that are inactive.</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;
    }
    .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>
