<template>
	<table class="table" style="font-family: monospace;" v-if="appointments && appointments.length > 0">
		<thead>
			<tr><th>Time</th><th>Clinic</th><th>Patient</th><th>Note</th><th>Assignee</th></tr>
			</thead>
		<tbody>
			<tr v-for="row in appointments" :style="{ backgroundColor: strHashHSL(row.Clinic, '90%') }">
				<td>{{row.ApptDate}}</td>
				<td>{{row.Clinic}}</td>
				<td v-if="production"><router-link :to="'/patient/$' + row.HRN">{{row.Name}} ${{row.HRN}}</router-link></td>
				<td v-else><router-link :title="unscramble(row.Name)" :to="'/patient/$' + row.Name.charAt(0) + row.HRN.slice(-4) + '?name=' + row.Name">{{row.Name}} ${{row.HRN}}</router-link></td>
				<td>{{row.NOTE}} [{{row.APPT_MADE_BY}} on {{row.DATE_APPT_MADE}}]</td>
				<td><Autocomplete :value="practitioner[row.Name]" @update:value="x => set_practitioner(row.Name, x)" :items="practitioner_list" /></td>
			</tr>
		</tbody>
	</table>
</template>

<script>
	import cookie from './cookie.mjs';
	import { uniq, strHashHSL } from './util.mjs';

	import Autocomplete from './Autocomplete.vue';

	function datefm(datestr) {
		var date = datestr ? new Date(datestr) : new Date();
		date = new Date(date.getTime() + date.getTimezoneOffset()*60000);
		return 10000*(date.getFullYear() - 1700) + 100*(date.getMonth() + 1) + date.getDate();
	}

	function strtr(s, a, b) {
		var res = '';
		for(var i = 0; i < s.length; ++i) {
			var j = a.indexOf(s.charAt(i));
			res += j >= 0 ? b.charAt(j) : s.charAt(i);
		}
		return res;
	}

	export default {
		components: {
			Autocomplete
		},
		props: {
			client: Object,
			selection: {
				type: Array,
				default: []
			},
			date_begin: String,
			date_end: String
		},
		data() {
			return {
				appointments: [],
				practitioner: {},
				production: true
			};
		},
		computed: {
			params() {
				return { selection: this.selection, date_begin: this.date_begin, date_end: this.date_end };
			},
			practitioner_list() {
				return this.practitioner ? uniq(Object.values(this.practitioner)).sort() : [];
			}
		},
		watch: {
			async params(value) {
				this.appointments = value.selection.length > 0 ? (await this.client.SDEC_CLINLET(value.selection.join('|') + '|', datefm(value.date_begin), datefm(value.date_end))).sort((a, b) => (new Date(a.ApptDate)) - (new Date(b.ApptDate))) : [];
			}
		},
		methods: {
			strHashHSL,
			unscramble(name) {
				return name.length > 0 ? (name.charAt(0) + strtr(name.substring(1), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'LKJIHGFEDCBAZYXWVUTSRQPONM')) : name;
			},
			set_practitioner(patient, practitioner) {
				this.practitioner[patient] = practitioner;
				cookie.set('vista.practitioner', JSON.stringify(this.practitioner), 1);
			}
		},
		async mounted() {
			var practitioner = cookie.get('vista.practitioner');
			if(practitioner) this.practitioner = JSON.parse(practitioner);
			this.production = (await this.client.serverinfo()).result.production == '1';
		}
	};
</script>
