<template>
	<div>
		<div class="card mb-3 shadow">
			<div class="card-header">Overview</div>
			<div class="card-body">
				<ViewResourceLookup :client="client" v-model:selection="selection" />
			</div>
		</div>
		<div class="card mb-3 shadow">
			<div class="card-header d-flex justify-content-between align-items-center">
				<span>Daily</span>
			</div>
			<div class="card-body">
				<table class="table" style="font-family: monospace;" v-if="appointments_daily.length > 0">
					<thead>
						<tr><th>Date</th><th>Count</th></tr>
					</thead>
					<tbody>
						<tr v-for="row in appointments_daily">
							<td>{{row.key}}</td>
							<td>{{row.values.length}}</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</template>

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

	import ViewResourceLookup from './ViewResourceLookup.vue';

	function dateonly(date) {
		return new Date(date.getFullYear(), date.getMonth(), date.getDate());
	}

	export default {
		components: {
			ViewResourceLookup
		},
		props: {
			client: Object
		},
		data() {
			var today = dateonly(new Date());
			return {
				appointments: [],
				production: true,
				date_begin: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
				date_end: new Date(today.getFullYear() + 1, today.getMonth(), today.getDate()),
				dow: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
			};
		},
		computed: {
			selection: {
				get() { return this.client.remotestate.resources ? (this.client.remotestate.resources.split(',').filter(x => x) || []) : [] },
				set(value) { this.client.remotestate.resources = value.join(','); }
			},
			appointments_daily() {
				return groupByArray(this.appointments, x => x.ApptDateDate);
			}
		},
		watch: {
			selection: {
				handler(value) { this.$nextTick(() => this.debounced_selection(value)); },
				immediate: true
			}
		},
		methods: {
			strHashHSL,
			strtr_unscramble,
			datefmt(date) {
				return date ? date.toLocaleDateString('sv-SE') : '';
			}
		},
		created() {
			this.debounced_selection = debounce(async function(value) {
				this.appointments = this.selection.length > 0 ? (await this.client.SDEC_CLINLET(this.selection.join('|') + '|', strftime_vista(this.date_begin), strftime_vista(this.date_end))) : [];
				this.appointments.forEach(x => {
					var obj = x.ApptDateObj = new Date(x.ApptDate);
					var date = x.ApptDateDate = obj.toLocaleDateString('sv-SE');
					//x.ApptDateWeek = obj.getFullYear() + '-' + Math.floor(((obj - new Date(obj.getFullYear(), 0, 1))/(24*60*60*1000) + obj.getDay())/7);
					//x.ApptDateMonth = obj.getFullYear() + '-' + obj.getMonth();
				});
			}, 500);
		},
		async mounted() {
			this.production = (await this.client.serverinfo()).result.production == '1';
		}
	};
</script>
