<script lang="ts">
	interface Props {
		log_lvl?: number;
		container_class_li?: string | Array<string>;
		// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
		link_to_type: string;
		link_to_id: string;
		lq__event_device_obj_li: any;
		auto_refresh?: number;
	}

	let {
		log_lvl = 0,
		container_class_li = [],
		link_to_type,
		link_to_id,
		lq__event_device_obj_li,
		auto_refresh = 90000
	}: Props = $props();

	// Imports
	import { onDestroy } from 'svelte';
	import type { key_val } from '$lib/stores/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import {
		events_loc,
		events_sess,
		events_slct,
		events_trigger,
		events_trig_kv
	} from '$lib/stores/ae_events_stores';
	import { events_func } from '$lib/ae_events_functions';

	import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';

	if (log_lvl) {
		console.log(`Event Device List: link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`);
	}

	// Variables
	let ae_promises: key_val = $state({
		load_ae_obj_id__event_device: {}
	});
	// let ae_tmp: key_val = {};
	// let ae_triggers: key_val = {};

	if (!$events_loc.pres_mgmt?.device_kv) {
		$events_loc.pres_mgmt.device_kv = {};
	}

	// *** Functions and Logic
	if (auto_refresh) {
		// Add a random number of seconds to the auto_refresh interval to prevent all clients from refreshing at the same time.
		let refresh_interval = auto_refresh + Math.floor(Math.random() * 15000);
		console.log(`Auto refresh interval: ${refresh_interval}`);
		if (typeof auto_refresh === 'number') {
			refresh_interval = auto_refresh;
		}

		let refresh_interval_id = setInterval(() => {
			console.log('Auto-refreshing Event Device List');
			events_func.load_ae_obj_li__event_device({
				api_cfg: $ae_api,
				for_obj_type: link_to_type,
				for_obj_id: link_to_id,
				log_lvl: log_lvl
			});
		}, refresh_interval);

		// This is needed to clear the interval when the component is destroyed to prevent multiple intervals from running.
		// This may need to change with Svelte v3.
		onDestroy(() => {
			console.log('the component is being destroyed');
			clearInterval(refresh_interval_id);
		});
	}
</script>

<section class="ae_comp event_device_obj_li {container_class_li}">
	<h3 class="h5">
		Devices:
		<span
			class="font-bold bg-success-100 px-4 border rounded-lg border-success-200"
			class:hidden={!$lq__event_device_obj_li?.length}
			title="Devices: {$lq__event_device_obj_li?.length ?? 'None'}"
		>
			<span class="fas fa-laptop m-1 text-neutral-800/80"></span>
			{@html $lq__event_device_obj_li?.length ? `${$lq__event_device_obj_li?.length}&times;` : ''}
		</span>

		{#if !$lq__event_device_obj_li?.length}
			<span class="text-sm text-gray-500 bg-gray-100 p-1 rounded-md border border-gray-200">
				<span class="fas fa-exclamation-triangle mx-1"></span>
				No devices available.
			</span>
		{/if}
	</h3>

	<!-- Show devices for this LiveQuery -->
	{#if $lq__event_device_obj_li?.length}
		<ul class="space-y-4 p-4 m-2 bg-gray-100 rounded-md">
			{#each $lq__event_device_obj_li as event_device_obj}
				<!-- svelte-ignore a11y_click_events_have_key_events -->
				<li
					class="space-y-2 border border-gray-400 p-2 rounded-md"
					class:dim={event_device_obj?.hide}
					class:hidden={event_device_obj?.hide && !$ae_loc.edit_mode}
				>
					<h4
						class="h5 rounded-md p-2 bg-gray-200 flex flex-row gap-1 items-center justify-between"
					>
						<span>
							<Element_ae_crud
								api_cfg={$ae_api}
								object_type={'event_device'}
								object_id={event_device_obj?.event_device_id}
								field_name={'name'}
								field_type={'text'}
								field_value={event_device_obj?.name}
								allow_null={false}
								hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
								outline_element={false}
								show_crud={false}
								display_inline={true}
								display_block_edit={true}
								class_li={''}
								on:ae_crud_updated={(e) => {
									console.log(`ae_crud_updated:`, e.detail);

									events_func
										.load_ae_obj_id__event_device({
											api_cfg: $ae_api,
											event_device_id: event_device_obj.event_device_id,
											log_lvl: 1
										})
										.then(function (load_results) {})
										.then(function (load_results) {
											// $events_trigger = 'load__event_device_obj_id';
											// $events_trig_kv['event_device_id'] = event_device_obj.event_device_id;
										});
								}}
							>
								<!-- <strong class="text-sm">Name/Title:</strong> -->
								<span class="fas fa-laptop m-1"></span>
								"{event_device_obj?.name}"
							</Element_ae_crud>
							<!-- "{event_device_obj.name}" -->
							{#if event_device_obj?.code && !$events_loc.pres_mgmt?.hide__device_code}
								<span
									class="text-sm text-gray-500 bg-yellow-100 p-1 rounded-md border border-yellow-200"
									title="Device code {event_device_obj?.code}"
								>
									<span class="fas fa-barcode"></span>
									{event_device_obj?.code ?? ''}
								</span>
							{/if}
						</span>

						<span>
							<span>
								{#if event_device_obj?.alert}
									<!-- {event_device_obj.alert} -->
									<span
										class="text-red-500 bg-red-200 p-1 rounded-md border border-red-200 text-center"
										title={event_device_obj.alert_msg}
									>
										<span class="fas fa-exclamation-triangle mx-1"></span>
									</span>
								{/if}
								{#if event_device_obj?.status}
									<!-- {event_device_obj.status} -->
									<span
										class="text-blue-500 bg-blue-200 p-1 rounded-md border border-blue-200 text-center"
										title={event_device_obj.status_msg}
									>
										<span class="fas fa-laptop-code mx-1"></span>
									</span>
								{/if}
								{#if event_device_obj?.record_status}
									<!-- {event_device_obj.record_status} -->
									<span
										class="text-orange-500 bg-orange-200 p-1 rounded-md border border-orange-200 text-center"
										title={event_device_obj.record_status_msg}
									>
										<span class="fas fa-camera mx-1"></span>
									</span>
								{/if}
							</span>

							<button
								type="button"
								onclick={() => {
									console.log('Refresh device info:', event_device_obj);
									ae_promises.load_ae_obj_id__event_device[event_device_obj.event_device_id] =
										events_func.load_ae_obj_id__event_device({
											api_cfg: $ae_api,
											event_device_id: event_device_obj.event_device_id,
											log_lvl: 0
										});
								}}
								class="btn btn-sm preset-tonal-surface hover:preset-filled-surface-500 transition-all hover:transition-all *:hover:inline text-xs"
							>
								{#await ae_promises.load_ae_obj_id__event_device[event_device_obj.event_device_id]}
									<span class="fas fa-spinner fa-spin mx-1"></span>
								{:then load_results}
									<span class="fas fa-sync-alt mx-1"></span>
								{:catch error}
									<span class="fas fa-exclamation-triangle mx-1"></span>
									<span class="hidden">Error</span>
								{/await}
								<span class="hidden">Refresh</span>
							</button>

							<button
								type="button"
								onclick={() => {
									console.log('Show/Hide Device');
									if (!$events_loc.pres_mgmt.device_kv) {
										$events_loc.pres_mgmt.device_kv = {
											[event_device_obj.event_device_id]: { collapse: true }
										};
									} else if (!$events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id]) {
										$events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id] = {
											collapse: true
										};
									} else {
										$events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id].collapse =
											!$events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id].collapse;
									}
								}}
								class="btn btn-sm preset-tonal-surface border border-surface-500 hover:preset-filled-surface-500 transition-all hover:transition-all *:hover:inline text-xs"
								class:preset-tonal-warning={$events_loc.pres_mgmt?.device_kv[
									event_device_obj.event_device_id
								]?.collapse}
							>
								{#if $events_loc.pres_mgmt.device_kv && $events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id]?.collapse}
									<!-- <span class="fas fa-minus mx-1"></span> -->
									<span class="fas fa-chevron-up m-1"></span>
									<span class="hidden">Show?</span>
								{:else}
									<span class="fas fa-chevron-down m-1"></span>
									<!-- <span class="fas fa-plus mx-1"></span> -->
									<!-- <span>Device</span> -->
								{/if}
							</button>
						</span>
					</h4>

					<div
						class:hidden={$events_loc.pres_mgmt.device_kv &&
							$events_loc.pres_mgmt.device_kv[event_device_obj.event_device_id]?.collapse}
					>
						<div class="flex flex-col gap-1">
							<div
								class="text-red-500 bg-red-200 p-1 rounded-md border border-red-400 text-center"
								class:hidden={!event_device_obj?.alert && !event_device_obj?.alert_msg}
							>
								<div class="flex flex-row items-center justify-between">
									<span class="fas fa-exclamation-triangle mx-1"></span>
									<strong class="text-bold">
										{event_device_obj?.alert ? 'Alert' : 'No Alert'}
									</strong>
									<span class="fas fa-exclamation-triangle mx-1"></span>
								</div>
								<div class="font-mono">
									<span class="fas fa-comment-dots mx-1"></span>
									{@html event_device_obj?.alert_msg ?? 'No message'}
								</div>
								{#if event_device_obj?.alert_on}
									<div class="text-sm text-gray-500">
										Datetime: {ae_util.iso_datetime_formatter(
											event_device_obj?.alert_on,
											'time_iso_12_tz'
										)}
									</div>
								{/if}
							</div>

							<div
								class="text-blue-500 bg-blue-200 p-1 rounded-md border border-blue-400 text-center"
								class:hidden={!event_device_obj?.status && !event_device_obj?.status_msg}
							>
								<div class="flex flex-row items-center justify-between">
									<span class="fas fa-laptop-code mx-1"></span>
									<strong class="text-bold">
										{event_device_obj?.status ? event_device_obj?.status : 'No Status'}
									</strong>
									<span class="fas fa-laptop-code mx-1"></span>
								</div>
								<div class="font-mono">
									<span class="fas fa-comment-dots mx-1"></span>
									{@html event_device_obj?.status_msg ?? 'No message'}
								</div>
								{#if event_device_obj?.status_on}
									<div class="text-sm text-gray-500">
										Datetime: {ae_util.iso_datetime_formatter(
											event_device_obj?.status_on,
											'time_iso_12_tz'
										)}
									</div>
								{/if}
							</div>

							<div
								class="text-orange-500 bg-orange-200 p-1 rounded-md border border-orange-400 text-center"
								class:hidden={!event_device_obj?.record_status &&
									!event_device_obj?.record_status_msg}
							>
								<div class="flex flex-row items-center justify-between">
									<span class="fas fa-camera mx-1"></span>
									<!-- The recording status should be an ISO timestamp if it is recording. We need to check if it is a datetime string first. -->
									{#if event_device_obj?.record_status && event_device_obj?.record_status.length > 10}
										{ae_util.iso_datetime_formatter(
											event_device_obj?.record_status,
											'time_iso_12_tz'
										)}
										<!-- Show number of second and minutes since last recording status update. -->
									{:else if event_device_obj?.record_status}
										{event_device_obj?.record_status}
									{:else}
										No Recording Status
									{/if}
									<span class="fas fa-camera mx-1"></span>
								</div>
								<div class="font-mono text-black">
									<span class="fas fa-comment-dots mx-1"></span>
									{@html event_device_obj?.record_status_msg ?? 'No message'}
								</div>
								{#if event_device_obj?.record_status_on}
									<div class="text-sm text-gray-500">
										Datetime: {ae_util.iso_datetime_formatter(
											event_device_obj?.record_status_on,
											'time_iso_12_tz'
										)}
									</div>
								{/if}
							</div>

							<div class="flex flex-col gap-1 text-gray-500 bg-gray-100">
								<span>
									<strong class="text-sm">hostname:</strong>
									{event_device_obj?.info_hostname}
								</span>
								<span>
									<strong class="text-sm">IPs:</strong>
									{event_device_obj?.info_ip_list}
								</span>
							</div>
							<div class="text-sm text-gray-500 bg-gray-100">
								Last updated:
								<span>
									<span>
										{ae_util.iso_datetime_formatter(event_device_obj?.updated_on, 'dddd')},
									</span>
									<span>
										{ae_util.iso_datetime_formatter(
											event_device_obj?.updated_on,
											'date_long_month_day'
										)}
									</span>
								</span>
								@
								<span
									class="px-1"
									class:bg-yellow-200={ae_util.is_datetime_recent({
										datetime: event_device_obj?.updated_on,
										minutes: 30
									})}
									class:bg-green-200={ae_util.is_datetime_recent({
										datetime: event_device_obj?.updated_on,
										minutes: 240
									})}
									class:bg-blue-200={ae_util.is_datetime_recent({
										datetime: event_device_obj?.updated_on,
										minutes: 2880
									})}
								>
									{ae_util.iso_datetime_formatter(event_device_obj?.updated_on, 'time_iso_12_tz')}
								</span>

								{#if event_device_obj?.heartbeat}
									<span class="fas fa-heartbeat mx-1"></span>
									Heartbeat:
									<span
										class="px-1"
										class:bg-yellow-200={ae_util.is_datetime_recent({
											datetime: event_device_obj?.heartbeat,
											minutes: 30
										})}
										class:bg-green-200={ae_util.is_datetime_recent({
											datetime: event_device_obj?.heartbeat,
											minutes: 240
										})}
										class:bg-blue-200={ae_util.is_datetime_recent({
											datetime: event_device_obj?.heartbeat,
											minutes: 2880
										})}
									>
										{ae_util.iso_datetime_formatter(event_device_obj?.heartbeat, 'time_iso_12_tz')}
									</span>
								{/if}
							</div>
						</div>

						<div class:hidden={!$events_loc.pres_mgmt.show_content__device_description}>
							<Element_ae_crud
								api_cfg={$ae_api}
								object_type={'event_device'}
								object_id={event_device_obj?.event_device_id}
								field_name={'description'}
								field_type={'textarea'}
								field_value={event_device_obj?.description}
								allow_null={false}
								hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
								outline_element={false}
								show_crud={false}
								display_inline={true}
								display_block_edit={true}
								textarea_rows={15}
								class_li={''}
								on:ae_crud_updated={(e) => {
									console.log(`ae_crud_updated:`, e.detail);

									events_func.load_ae_obj_id__event_device({
										api_cfg: $ae_api,
										event_device_id: event_device_obj.event_device_id,
										log_lvl: 1
									});
								}}
							>
								<strong class="text-sm"> Description: </strong>

								{#if event_device_obj?.description}
									<button
										type="button"
										onclick={() => {
											console.log('Show/Hide Description');
											if (
												$events_sess.pres_mgmt.show_content__device_description ==
												event_device_obj.event_device_id
											) {
												$events_sess.pres_mgmt.show_content__device_description = null;

												// Was testing with LiveQuery
												$events_slct.event_device_id = null;
											} else {
												$events_sess.pres_mgmt.show_content__device_description =
													event_device_obj.event_device_id;

												// Was testing with LiveQuery
												$events_slct.event_device_id = event_device_obj.event_device_id;
											}
										}}
										class="btn btn-sm preset-tonal-surface hover:preset-filled-surface-500 text-xs"
									>
										{#if $events_sess.pres_mgmt.show_content__device_description == event_device_obj.event_device_id}
											<span class="fas fa-eye-slash mx-1"></span>
											<span>Hide Description</span>
										{:else}
											<span class="fas fa-eye mx-1"></span>
											<span>Show</span>
										{/if}
									</button>

									<pre
										class="whitespace-pre-wrap p-2 bg-gray-100 rounded-md"
										class:hidden={$events_sess.pres_mgmt.show_content__device_description !==
											event_device_obj.event_device_id}>{event_device_obj.description}</pre>
								{:else}
									{@html ae_snip.html__not_set}
								{/if}
								<!-- {:else}
                <div class="text-sm text-gray-500 bg-gray-100 p-1 rounded-md border border-gray-200"
                    class:hidden={!$ae_loc.administrator_access}
                    >
                    <span class="fas fa-exclamation-triangle mx-1"></span>
                    No description provided.
                </div>
            {/if} -->
							</Element_ae_crud>
						</div>
					</div>
					<!-- End of device content -->
				</li>
			{/each}
		</ul>
	{:else}
		<!-- <p class:hidden={display_mode != 'default'}>
        No devices available to show at this time
    </p> -->
	{/if}
</section>
