<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, untrack } 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_sess,
    events_slct,
    events_trigger,
    events_trig_kv
} from '$lib/stores/ae_events_stores';
import { pres_mgmt_loc } from '$lib/stores/ae_events_stores__pres_mgmt.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';

import Element_ae_obj_field_editor from '$lib/elements/element_ae_obj_field_editor.svelte';
import {
    Barcode,
    Camera,
    ChevronDown,
    ChevronUp,
    Eye,
    EyeOff,
    HeartPulse,
    Laptop,
    LoaderCircle,
    MessageCircle,
    RefreshCw,
    TriangleAlert
} from '@lucide/svelte';
$effect(() => {
    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 (!pres_mgmt_loc.current.device_kv) {
    pres_mgmt_loc.current.device_kv = {};
}

// *** Functions and Logic
let refresh_interval_id: any;

$effect(() => {
    if (auto_refresh) {
        untrack(() => {
            if (refresh_interval_id) clearInterval(refresh_interval_id);

            // 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);
            if (log_lvl)
                console.log(`Auto refresh interval: ${refresh_interval}`);

            refresh_interval_id = setInterval(() => {
                if (log_lvl) 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);
        });
    }
});

onDestroy(() => {
    if (refresh_interval_id) clearInterval(refresh_interval_id);
});
</script>

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

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

    <!-- Show devices for this LiveQuery -->
    {#if $lq__event_device_obj_li?.length}
        <ul class="m-2 space-y-4 rounded-md bg-gray-100 p-4">
            {#each $lq__event_device_obj_li as event_device_obj (event_device_obj.event_device_id)}
                <!-- svelte-ignore a11y_click_events_have_key_events -->
                <li
                    class="space-y-2 rounded-md border border-gray-400 p-2"
                    class:dim={event_device_obj?.hide}
                    class:hidden={event_device_obj?.hide && !$ae_loc.edit_mode}>
                    <h4
                        class="h5 flex flex-row items-center justify-between gap-1 rounded-md bg-gray-200 p-2">
                        <span>
                            <Element_ae_obj_field_editor
                                object_type={'event_device'}
                                object_id={event_device_obj?.event_device_id}
                                field_name={'name'}
                                field_type={'text'}
                                current_value={event_device_obj?.name}
                                display_block={true}
                                on_success={() =>
                                    events_func.load_ae_obj_id__event_device({
                                        api_cfg: $ae_api,
                                        event_device_id:
                                            event_device_obj.event_device_id,
                                        log_lvl: 1
                                    })}>
                                <Laptop size="1em" class="m-1" />
                                "{event_device_obj?.name}"
                            </Element_ae_obj_field_editor>
                            <!-- "{event_device_obj.name}" -->
                            {#if event_device_obj?.code && !pres_mgmt_loc.current.hide__device_code}
                                <span
                                    class="rounded-md border border-yellow-200 bg-yellow-100 p-1 text-sm text-gray-500"
                                    title="Device code {event_device_obj?.code}">
                                    <Barcode size="1em" />
                                    {event_device_obj?.code ?? ''}
                                </span>
                            {/if}
                        </span>

                        <span>
                            <span>
                                {#if event_device_obj?.alert}
                                    <!-- {event_device_obj.alert} -->
                                    <span
                                        class="rounded-md border border-red-200 bg-red-200 p-1 text-center text-red-500"
                                        title={event_device_obj.alert_msg}>
                                        <TriangleAlert
                                            size="1em"
                                            class="mx-1" />
                                    </span>
                                {/if}
                                {#if event_device_obj?.status}
                                    <!-- {event_device_obj.status} -->
                                    <span
                                        class="rounded-md border border-blue-200 bg-blue-200 p-1 text-center text-blue-500"
                                        title={event_device_obj.status_msg}>
                                        <Laptop size="1em" class="mx-1" />
                                    </span>
                                {/if}
                                {#if event_device_obj?.record_status}
                                    <!-- {event_device_obj.record_status} -->
                                    <span
                                        class="rounded-md border border-orange-200 bg-orange-200 p-1 text-center text-orange-500"
                                        title={event_device_obj.record_status_msg}>
                                        <Camera size="1em" class="mx-1" />
                                    </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 text-xs transition-all hover:transition-all *:hover:inline">
                                {#await ae_promises.load_ae_obj_id__event_device[event_device_obj.event_device_id]}
                                    <LoaderCircle
                                        size="1em"
                                        class="mx-1 animate-spin" />
                                {:then load_results}
                                    <RefreshCw size="1em" class="mx-1" />
                                {:catch error}
                                    <TriangleAlert size="1em" class="mx-1" />
                                    <span class="hidden">Error</span>
                                {/await}
                                <span class="hidden">Refresh</span>
                            </button>

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

                    <div
                        class:hidden={pres_mgmt_loc.current.device_kv &&
                            pres_mgmt_loc.current.device_kv[
                                event_device_obj.event_device_id
                            ]?.collapse}>
                        <div class="flex flex-col gap-1">
                            <div
                                class="rounded-md border border-red-400 bg-red-200 p-1 text-center text-red-500"
                                class:hidden={!event_device_obj?.alert &&
                                    !event_device_obj?.alert_msg}>
                                <div
                                    class="flex flex-row items-center justify-between">
                                    <TriangleAlert size="1em" class="mx-1" />
                                    <strong class="text-bold">
                                        {event_device_obj?.alert
                                            ? 'Alert'
                                            : 'No Alert'}
                                    </strong>
                                    <TriangleAlert size="1em" class="mx-1" />
                                </div>
                                <div class="font-mono">
                                    <MessageCircle size="1em" class="mx-1" />
                                    {@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="rounded-md border border-blue-400 bg-blue-200 p-1 text-center text-blue-500"
                                class:hidden={!event_device_obj?.status &&
                                    !event_device_obj?.status_msg}>
                                <div
                                    class="flex flex-row items-center justify-between">
                                    <Laptop size="1em" class="mx-1" />
                                    <strong class="text-bold">
                                        {event_device_obj?.status
                                            ? event_device_obj?.status
                                            : 'No Status'}
                                    </strong>
                                    <Laptop size="1em" class="mx-1" />
                                </div>
                                <div class="font-mono">
                                    <MessageCircle size="1em" class="mx-1" />
                                    {@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="rounded-md border border-orange-400 bg-orange-200 p-1 text-center text-orange-500"
                                class:hidden={!event_device_obj?.record_status &&
                                    !event_device_obj?.record_status_msg}>
                                <div
                                    class="flex flex-row items-center justify-between">
                                    <Camera size="1em" class="mx-1" />
                                    <!-- 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}
                                    <Camera size="1em" class="mx-1" />
                                </div>
                                <div class="font-mono text-black">
                                    <MessageCircle size="1em" class="mx-1" />
                                    {@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 bg-gray-100 text-gray-500">
                                <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="bg-gray-100 text-sm text-gray-500">
                                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}
                                    <HeartPulse size="1em" class="mx-1" />
                                    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={!pres_mgmt_loc.current.show_content__device_description}>
                            <Element_ae_obj_field_editor
                                object_type={'event_device'}
                                object_id={event_device_obj?.event_device_id}
                                field_name={'description'}
                                field_type={'textarea'}
                                current_value={event_device_obj?.description}
                                allow_null={true}
                                display_block={true}
                                textarea_rows={15}
                                on_success={() =>
                                    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}
                                            <EyeOff size="1em" class="mx-1" />
                                            <span>Hide Description</span>
                                        {:else}
                                            <Eye size="1em" class="mx-1" />
                                            <span>Show</span>
                                        {/if}
                                    </button>

                                    <pre
                                        class="rounded-md bg-gray-100 p-2 whitespace-pre-wrap"
                                        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_obj_field_editor>
                        </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>
