<script lang="ts">
// Imports
import { liveQuery } from "dexie";

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/api';

import { db_events } from "$lib/ae_events/db_events";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
// import { events_loc, events_sess, events_slct, events_trigger, events_trig_kv } from '$lib/ae_events_stores';
// import { events_func } from '$lib/ae_events_functions';
import MyClipboard from '$lib/e_app_clipboard.svelte';

// Exports
export let container_class_li: string|Array<string> = [];
export let event_file_id_random_li: Array<string> = [];
export let allow_basic: boolean = false;
export let allow_moderator: boolean = false;
// export let max_records: number = 100;
export let show_direct_download: boolean = false;
export let show_location_fields: boolean = false;
export let show_presentation_fields: boolean = false;
// export let show_presenter_fields: boolean = false;
export let show_session_fields: boolean = false;

// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'

// Variables
let ae_promises: key_val = {};

// *** Functions and Logic
// let lq__event_file_obj = liveQuery(
//     () => db_events.files.get($events_slct.event_file_id)
// );

let lq_kv__event_file_obj_li = liveQuery(
    () => db_events.files
    .bulkGet(event_file_id_random_li)
);

// Define the list of unacceptable characters if not using the default.
// const unacceptable_chars = /[ <>:"/\\|?*]/g;
</script>


<section class="ae_comp event_file_obj_tbl container {container_class_li}">


{#if event_file_id_random_li && $lq_kv__event_file_obj_li && $lq_kv__event_file_obj_li?.length > 0 && $lq_kv__event_file_obj_li?.length == event_file_id_random_li?.length}

<div class="overflow-auto space-y-2">
<h2 class="h3">
    <span class="text-base">
    Results:
    </span>

    {#if $lq_kv__event_file_obj_li.length}
    <span class="text-3xl font-bold bg-success-100 px-4 border rounded-lg border-success-200"
            title="Count {$lq_kv__event_file_obj_li.length ?? 'None'}"
            >
        <span class="fas fa-list-ol mx-4"></span>
        {$lq_kv__event_file_obj_li.length ?? 'None'}×
    </span>
    {/if}
</h2>

<table
    class="table table-auto table-striped  w-full text-xs lg:text-sm"
    >
    <thead
        class=""
        >
        <tr>
            <th class="px-4 py-2">
                Filename
                <!-- ({$lq_kv__event_file_obj_li?.length}&times;) -->
            </th>
            <th
                class="px-4 py-2"
                class:hidden={!show_direct_download}
                >
                Link
            </th>
            <th class="px-4 py-2">Size</th>
            <th class="px-4 py-2">Uploaded</th>
            {#if show_location_fields}
            <th class="px-4 py-2">Location</th>
            {/if}
            {#if show_session_fields}
            <th class="px-4 py-2">
                Session
            </th>
            <th class="px-4 py-2">Start datetime</th>
            {/if}
            {#if show_presentation_fields}
            <th class="px-4 py-2">Presentation</th>
            <th class="px-4 py-2">Presentation time</th>
            {/if}
            <th class="px-4 py-2">Name</th>
            <!-- <th class="px-4 py-2">Email</th> -->
            <!-- <th class="px-4 py-2">Agree</th> -->

        </tr>
    </thead>
    <tbody
        class="">
    {#each $lq_kv__event_file_obj_li as event_file_obj}
        <tr
            class:dim={event_file_obj?.hide}
            >
            <td class="px-4 py-2">


                <button
                    disabled={!allow_basic && !allow_moderator && !$ae_loc.trusted_access}
                    on:click={() => {
                        // ae_promises[event_file_obj?.event_file_id_random]
                        ae_promises[event_file_obj?.event_file_id_random] = api.download_hosted_file({
                            api_cfg: $ae_api,
                            hosted_file_id: event_file_obj?.hosted_file_id_random,
                            return_file: true,
                            filename: event_file_obj?.filename,
                            auto_download: true,
                            log_lvl: 0
                        });

                        // window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj?.event_file_id_random, filename: event_file_obj?.filename, auto_download: true }, '*');
                    }}
                    class="btn btn-sm preset-tonal-primary hover:preset-filled-primary-500 min-w-72"
                    title={`Download this file: ${event_file_obj?.filename} [API] -- SHA256 hash: ${event_file_obj?.hash_sha256.slice(0, 10)}...`}
                    >
                    {#await ae_promises[event_file_obj?.event_file_id_random]}
                        <span class="fas fa-spinner fa-spin mx-1"></span>
                        <span class="">
                            Downloading
                            {#if $ae_sess.api_download_kv[event_file_obj?.hosted_file_id_random]}
                                {$ae_sess.api_download_kv[event_file_obj?.hosted_file_id_random].percent_completed}%
                            {/if}
                            :
                        </span>
                    {:then}
                        <!-- <span class="fas fa-download mx-1"></span> -->
                        <span class="fas fa-{ae_util.file_extension_icon(event_file_obj?.extension)}"></span>
                        <!-- <span class="text-sm">
                        Download:
                        </span> -->
                    {/await}

                    <span class="grow">
                    {ae_util.shorten_filename({filename: event_file_obj?.filename, max_length: 30})}
                    </span>

                    <span
                        class="badge preset-tonal-success hover:preset-filled-success-500 text-sm"
                        class:hidden={!event_file_obj?.file_purpose}
                        >
                        {event_file_obj?.file_purpose}
                    </span>

                </button>
                <!-- {event_file_obj?.filename} -->
            </td>
            <td
                class="px-4 py-2 flex flex-col gap-0.5"
                class:hidden={!show_direct_download}
                >
                <div
                    class:hidden={!show_direct_download}
                    class="flex flex-row gap-0.5">
                    <span class="text-xs text-gray-500 w-32">
                        Original:
                    </span>
                    <a
                        href="{$ae_api.base_url}/event/file/{event_file_obj?.event_file_id_random}/download?filename={ae_util.clean_filename(event_file_obj?.filename)}&x_no_account_id_token=direct-download"
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs underline"
                        title={`Download this file:\n${ae_util.clean_filename(event_file_obj?.filename)}\n[API] SHA256: ${event_file_obj?.hash_sha256.slice(0, 10)}...\nHosted ID: ${event_file_obj?.hosted_file_id_random} Event File ID: ${event_file_obj?.event_file_id_random}`}
                        >
                        <span class="fas fa-download mx-1"></span>
                        <span class="hidden">
                        Download
                        </span>
                    </a>
                    <!-- <button
                        type="button"
                        use:clipboard={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${ae_util.clean_filename(event_file_obj?.filename)}&x_no_account_id_token=direct-download`)}
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs"
                        title="Copy the direct download file link: {ae_util.clean_filename(event_file_obj?.filename ?? 'unknown')}"
                        >
                        <span class="fas fa-copy mx-1"></span>
                        <span class="hidden">
                        Copy Link
                        </span>
                    </button> -->

                    <MyClipboard
                        value={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${ae_util.clean_filename(event_file_obj?.filename)}&x_no_account_id_token=direct-download`)}
                        btn_text="Copy Link"
                        btn_title="Copy the direct download file link: {ae_util.clean_filename(event_file_obj?.filename ?? 'unknown')}"
                        btn_class="btn btn-sm p-1 preset-tonal-secondary lg:text-xs"
                        ></MyClipboard>
                </div>

                <div
                    class="flex flex-row gap-0.5"
                    class:hidden={!show_direct_download}
                    >
                    <span class="text-xs text-gray-500 w-32">
                    Session Name:
                    </span>
                    <a
                        href="{$ae_api.base_url}/event/file/{event_file_obj?.event_file_id_random}/download?filename={event_file_obj?.event_session_code}-{ae_util.clean_filename(event_file_obj?.event_presentation_name).substring(0, 20)}-{ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.{event_file_obj?.extension}&x_no_account_id_token=direct-download"
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs underline"
                        title={`Download renamed with session name to: ${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_session_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}`}
                        >
                        <span class="fas fa-download mx-1"></span>
                        <span class="hidden">
                        Renamed
                        </span>
                    </a>
                    <!-- <button
                        type="button"
                        use:clipboard={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_session_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}&x_no_account_id_token=direct-download`)}
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs"
                        title="Copy the renamed file link"
                        >
                        <span class="fas fa-copy mx-1"></span>
                        <span class="hidden">
                        Copy Renamed
                        </span>
                    </button> -->
                    <MyClipboard
                        value={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_session_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}&x_no_account_id_token=direct-download`)}
                        btn_text="Copy Renamed"
                        btn_title="Copy the renamed file link"
                        btn_class="btn btn-sm p-1 preset-tonal-secondary lg:text-xs"
                        ></MyClipboard>
                </div>

                <div
                    class:hidden={!show_direct_download}
                    class="flex flex-row gap-0.5"
                    >
                    <span class="text-xs text-gray-500 w-32">
                    Presentation Name:
                    </span>
                    <a
                        href="{$ae_api.base_url}/event/file/{event_file_obj?.event_file_id_random}/download?filename={event_file_obj?.event_session_code}-{ae_util.clean_filename(event_file_obj?.event_presentation_name).substring(0, 20)}-{ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.{event_file_obj?.extension}&x_no_account_id_token=direct-download"
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs underline"
                        title={`Download renamed with presentation name to: ${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_presentation_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}`}
                        >
                        <span class="fas fa-download mx-1"></span>
                        <span class="hidden">
                        Renamed
                        </span>
                    </a>
                    <!-- <button
                        type="button"
                        use:clipboard={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_presentation_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}&x_no_account_id_token=direct-download`)}
                        class="btn btn-sm p-1 preset-tonal-secondary *:hover:inline lg:text-xs"
                        title="Copy the renamed file link"
                        >
                        <span class="fas fa-copy mx-1"></span>
                        <span class="hidden">
                        Copy Renamed
                        </span>
                    </button> -->
                    <MyClipboard
                        value={encodeURI(`${$ae_api.base_url}/event/file/${event_file_obj?.event_file_id_random}/download?filename=${event_file_obj?.event_session_code}-${ae_util.clean_filename(event_file_obj?.event_presentation_name).substring(0, 20)}-${ae_util.clean_filename(event_file_obj?.event_presenter_full_name)}.${event_file_obj?.extension}&x_no_account_id_token=direct-download`)}
                        btn_text="Copy Renamed"
                        btn_title="Copy the renamed file link"
                        btn_class="btn btn-sm p-1 preset-tonal-secondary lg:text-xs"
                        ></MyClipboard>
                </div>

            </td>
            <td class="px-4 py-2">{ae_util.format_bytes(event_file_obj?.file_size)}</td>
            <td
                class="px-4 py-2"

                >
                <div>
                    <span>
                    {ae_util.iso_datetime_formatter(event_file_obj?.created_on, 'dddd')}
                    </span>
                    <span>
                    {ae_util.iso_datetime_formatter(event_file_obj?.created_on, 'date_long_month_day')}
                    </span>
                </div>
                <span
                    class:bg-yellow-200={ae_util.is_datetime_recent({datetime: event_file_obj?.created_on, minutes: 30})}
                    class:bg-green-200={ae_util.is_datetime_recent({datetime: event_file_obj?.created_on, minutes: 240})}
                    class:bg-blue-200={ae_util.is_datetime_recent({datetime: event_file_obj?.created_on, minutes: 2880})}
                    >
                {ae_util.iso_datetime_formatter(event_file_obj?.created_on, 'time_12_short')}
                </span>
            </td>
            {#if show_location_fields}
            <td class="px-4 py-2 lg:text-xs">
                {#if event_file_obj?.event_location_id}
                <!-- <span class="fas fa-map-marker-alt"></span> -->
                {event_file_obj?.event_location_name}
                {:else}
                    {@html ae_snip.html__not_set}
                {/if}
            </td>
            {/if}

            {#if show_session_fields}
            <td class="px-4 py-2 lg:text-xs">
                <span class="fas fa-chalkboard-teacher"></span>
                <a
                    href="/events/{event_file_obj?.event_id}/session/{event_file_obj?.event_session_id}"
                    class="text-blue-500 underline hover:text-blue-800"
                    >
                    {event_file_obj?.event_session_name}
                </a>
            </td>
            <td class="px-4 py-2">{ae_util.iso_datetime_formatter(event_file_obj?.event_session_start_datetime, 'datetime_iso_12_no_seconds')}</td>
            {/if}
            {#if show_presentation_fields}
            <td class="px-4 py-2 lg:text-xs">
                {#if event_file_obj?.event_presentation_id}
                {event_file_obj?.event_presentation_name}
                {:else}
                    {@html ae_snip.html__not_set}
                {/if}
            </td>
            <td class="px-4 py-2">
                {#if event_file_obj?.event_presentation_id}
                {ae_util.iso_datetime_formatter(event_file_obj?.event_presentation_start_datetime, 'time_12_short')}
                {:else}
                    {@html ae_snip.html__not_set}
                {/if}
            </td>
            {/if}
            <td class="px-4 py-2">
                {#if event_file_obj?.event_presenter_id}
                <span class="fas fa-user"></span>
                <a
                    href="/events/{event_file_obj?.event_id}/presenter/{event_file_obj?.event_presenter_id}"
                    class="text-blue-500 underline hover:text-blue-800"
                    >
                    {event_file_obj?.event_presenter_full_name}
                </a>
                {:else}
                    <!-- <span class="text-gray-500">--</span> -->
                    {@html ae_snip.html__not_set}
                {/if}
            </td>
            <!-- <td class="px-4 py-2">
                <span class="fas fa-envelope"></span>
                <a
                    href="mailto:{event_file_obj?.email}"
                    class="text-blue-500 underline hover:text-blue-800"
                    >
                    {event_file_obj?.email}
                </a>
            </td> -->
            <!-- <td class="px-4 py-2">{event_file_obj?.agree ? 'Yes' : 'No'}</td> -->

        </tr>
    {/each}
    </tbody>
</table>
</div>

{:else}

<p class="text-sm">
    No files available to show.
</p>

{/if}

</section>


<style>
.dim {
    opacity: 0.5;
    color: #999;
}
</style>
