<template>
	<table class="table table-striped">
		<tbody v-if="resultset.length > 0">
			<tr v-for="item in resultset" :class="{ 'table-active': (x_modelValue) && (x_modelValue.IEN) && (x_modelValue.datetime) && (item.location_ien == x_modelValue.IEN) && (item.datetime == x_modelValue.datetime) }" @click="x_modelValue = { IEN: item.location_ien, location: item.location, datetime: item.datetime, appointment_ien: item.IEN }">
				<td>{{item.location}}</td>
				<td>#{{item.location_ien}}</td>
				<td style="text-align: right;">{{item.status}}</td>
				<td style="text-align: right;">{{item.datestr}} {{item.timestr}}</td>
			</tr>
		</tbody>
		<tfoot v-else>
			<tr><td style="text-align: center;">No encounters in range</td></tr>
		</tfoot>
	</table>
</template>

<style scoped>
	td {
		cursor: default;
	}
	.table-active, .table-active:nth-of-type(odd) > * {
		color: #fff;
		background-color: #0d6efd;
	}
</style>

<script>
	import { strftime_vista, strptime_vista, debounce } from './util.mjs';

	function date_down(d) {
		return new Date(d.getFullYear(), d.getMonth(), d.getDate());
	}

	function date_up(d) {
		return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);
	}

	export default {
		props: {
			client: Object,
			dfn: String,
			date_begin: Date,
			date_end: Date,
			modelValue: Object
		},
		emits: {
			'update:modelValue': Object
		},
		data() {
			return {
				resultset: [],
				x_modelValue: this.modelValue
			};
		},
		computed: {
			params() {
				return { dfn: this.dfn, date_begin: strftime_vista(date_down(this.date_begin)), date_end: strftime_vista(date_up(this.date_end)) };
			}
		},
		watch: {
			modelValue(value) { this.x_modelValue = value; },
			x_modelValue(value) { this.$emit('update:modelValue', value); },
			params: {
				async handler(value) {
					console.log(value);
					try {
						this.resultset = (await this.client.ORWCV_VST(value.dfn, value.date_begin, value.date_end, '')).map(item => Object.assign({
							datestr: strptime_vista(item.datetime).toLocaleDateString('sv-SE'),
							timestr: strptime_vista(item.datetime).toLocaleTimeString('en-GB'),
							location_ien: item.apptinfo.split(';')[2]
						}, item)).reverse();
					} catch(ex) {
						this.resultset = [];
						console.warn(ex);
					}
				}, immediate: true
			}
		}
	};
</script>
