<script lang="ts">

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/api';
import Element_ae_crud from '$lib/element_ae_crud.svelte';
import Launcher_file_cont from './launcher_file_cont.svelte';
import Launcher_presenter_view from './launcher_presenter_view.svelte';

import { liveQuery } from "dexie";
// import { core_func } from '$lib/ae_core_functions';
// import { db_core } from "$lib/db_core";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { db_events } from "$lib/db_events";
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';

// export let slct_event_session_id: string;

// export let lq__event_file_obj: any;
// export let lq_get__event_file_obj_li: any;
// export let lq__event_location_obj: any;
// export let lq__event_presentation_obj: any;
// export let lq_get__event_presentation_obj_li: any;
// export let lq__event_presenter_obj: any;
// export let lq_get__event_presenter_obj_li: any;
export let lq__event_session_obj: any;

// let load_event_session_obj = events_func.load_ae_obj_id__event_session({
//     api_cfg: $ae_api,
//     event_session_id: $events_slct.event_session_id,
//     inc_presenter_li: false,
//     try_cache: true,
//     log_lvl: 1
// });

// let lq__event_session_obj = liveQuery(
//     () => db_events.sessions.get(slct_event_session_id)
// );

// let lq__event_session_obj = liveQuery(
//     () => db_events.sessions.get($events_slct.event_session_id)
// );

// import Event_launcher_file_cont from './launcher_file_cont.svelte';


export let hide_description: boolean = true;
export let show_designations: boolean = false;
export let show_email: boolean = false;

// Event File
let lq__event_file_obj_li = liveQuery(
    () => db_events.files
        // .where('event_session_id_random')
        .where('for_id_random')
        .equals($events_slct.event_session_id)
        .sortBy('filename')
);

// Does not refresh when the event_file_id_li_json changes.
// let lq_get__event_file_obj_li = liveQuery(
//     () => db_events.files
//         .bulkGet($lq__event_session_obj?.event_file_id_li_json ?? [''])
// );
// console.log(`$lq__event_session_obj?.event_file_id_li_json = `, $lq__event_session_obj?.event_file_id_li_json);

// Event Presentation
// let lq__event_presentation_obj = liveQuery(
//     () => db_events.presentations
//         .get($events_slct.event_presentation_id)
// );

$: lq__event_presentation_obj_li = liveQuery(async () => {
    let results = await db_events.presentations
        .where('event_session_id_random')
        .equals($events_slct.event_session_id)
        .sortBy('start_datetime');
        // .sortBy('name')

    return results;
});

// FIX! This id list needs to be updated. It is currently commented out in the menu_session_list.svelte file.
// let lq_get__event_presentation_obj_li = liveQuery(
//     () => db_events.presentations
//         .bulkGet($events_slct.id_li__event_presentation)
// );


$: lq__event_presenter_obj_li = liveQuery(async () => {
    let results = await db_events.presenters
        .where('event_session_id_random')
        .equals($events_slct.event_session_id)
        .sortBy('full_name');

    return results;
});

let show_modal_upload_files: boolean = false;
let link_to_type: null|string = null;
let link_to_id: null|string = null;


let ae_promises: key_val = {};
$events_slct.id_li__event_presenter = [];
// await tick();
ae_promises[$events_slct.event_session_id] = events_func.load_ae_obj_li__event_presenter({
    api_cfg: $ae_api,
    for_obj_type: 'event_session',
    for_obj_id: $events_slct.event_session_id,
    // inc_file_li: false,
    params: {qry__enabled: 'enabled', qry__limit: 550},
    try_cache: true,
    log_lvl: 1,
})
.then(async function (load_results) {
    console.log(`load_results = `, load_results);

    let event_presenter_id_li = [];

    let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

    for (let i = 0; i < load_results.length; i++) {
        let event_presenter_obj = load_results[i];
        let event_presenter_id_random = event_presenter_obj.event_presenter_id_random;
        tmp_li.push(event_presenter_id_random);
    }
    event_presenter_id_li = tmp_li;
    console.log(`event_presenter_id_li:`, event_presenter_id_li);
    $events_slct.id_li__event_presenter = event_presenter_id_li;
    // $events_slct = {...$events_slct};
    // await tick();

    return load_results;
});

</script>

<!-- {$events_slct.event_session_id} -->

<section class="event_launcher_session_view grow w-full space-y-2">
    <!-- <slot name="event_session_message">event session message</slot> -->

    {#if $lq__event_session_obj && $lq__event_session_obj.event_session_id_random}
        <header class="event_session_about text-center border-b-2 border-gray-400">

            <h3
                class="event_session_datetimes"
                >
                <button
                    type="button"
                    on:click={() => {
                        if ($events_loc.launcher.time_format == 'time_12_short') {
                            // $events_loc.launcher.datetime_format = 'datetime_long';
                            $events_loc.launcher.time_format = 'time_short';
                            $events_loc.launcher.time_hours = 24;
                        } else {
                            $events_loc.launcher.time_format = 'time_12_short';
                            // $events_loc.launcher.datetime_format = 'datetime_12_long';
                            $events_loc.launcher.time_hours = 12;
                        }
                    }}
                    >
                    <strong>{ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, 'week_long')}</strong>
                    <span class="font-normal">
                        {ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, 'date_long_month_day')}
                    </span>
                    <strong>{ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, $events_loc.launcher.time_format)}</strong>
                    <span class="font-normal">
                        &ndash;
                        {ae_util.iso_datetime_formatter($lq__event_session_obj.end_datetime, $events_loc.launcher.time_format)}
                    </span>
                </button>
            </h3>
            <h2 class="text-xl">

                {$lq__event_session_obj?.name}
                {#if $lq__event_session_obj?.code}
                <span class="text-base text-gray-500 font-normal p-1"
                    title="Session code {$lq__event_session_obj.code}"
                    >
                    <span class="fas fa-barcode"></span>
                    {$lq__event_session_obj?.code}
                </span>
                {/if}

            </h2>
        </header>

        <!-- <section class="event_session_description text-xs" class:d_none="{hide_description}">
            {@html $lq__event_session_obj.description}
        </section> -->

        {#if !$lq__event_session_obj?.file_count_all}
            <p class="text-2xl text-center text-red-500 font-bold">
                <span class="fas fa-exclamation-triangle"></span>
                Warning
                <span class="fas fa-exclamation-triangle"></span>
                <br>
                No files available show for this session.

            </p>
        {/if}


        {#if $lq__event_file_obj_li && $lq__event_file_obj_li.length }
        <section class="event_session_file_list">
            <div>
                <div class="text-xs"><strong>
                    <span class="fas fa-file-archive"></span>
                    Session Files:
                    {#if $ae_loc.administrator_access}
                        ({$lq__event_file_obj_li?.length})
                    {/if}
                </strong></div>
                <!-- {#if $ae_loc.trusted_access || $events_loc.launcher.trusted_access}
                <button on:click={async () => {
                    show_modal_upload_files = true;
                    link_to_type = 'event_session';
                    link_to_id = $lq__event_session_obj.event_session_id_random;
                    }}
                    type="button" class="ae_btn btn_outline_warning btn_xs" title="Upload updated or additional files"
                    >
                    <span class="fas fa-upload"></span> Upload Session File(s)
                </button>
                {/if} -->
            </div>
            <ul>
            {#each $lq__event_file_obj_li as event_file_obj, index}
                <li
                    class="flex flex-row justify-center gap-1"
                    class:hidden={!$events_loc.launcher.show_content__hidden_files && event_file_obj.hide}
                    >
                    <button
                        disabled={!$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 lg:btn-md variant-soft-secondary hover:variant-filled-primary min-w-72 lg:min-w-96"
                        title={`Download this file:\n${event_file_obj.filename}\n[API] SHA256: ${event_file_obj.hash_sha256.slice(0, 10)}... Hosted ID: ${event_file_obj.hosted_file_id_random} Event File ID: ${event_file_obj.event_file_id_random}`}
                        >
                        {#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 variant-glass-success hover:variant-filled-success text-sm"
                            class:hidden={!event_file_obj.file_purpose}
                            >
                            {event_file_obj.file_purpose}
                        </span>
                    </button>
                    <!-- <Launcher_file_cont {event_file_obj} hide_created_on={false} show_bak_download={($ae_loc.trusted_access || $events_loc.launcher.trusted_access)} open_file_as={$lq__event_session_obj.type_code} poster_title={$lq__event_session_obj.title} /> -->


                    <!-- <a
                        href="{$ae_api.base_url}/event/file/{event_file_obj.event_file_id_random}/download?filename={event_file_obj.filename}&x_no_account_id_token=direct-download"
                        class="btn btn-sm variant-soft-secondary m-0.5 *:hover:inline"
                        class:hidden={!ae_tmp.show__direct_download}
                        title={`Download this file:\n${event_file_obj.filename}\n[API] SHA256: ${event_file_obj.hash_sha256.slice(0, 10)}... Hosted 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>
                        <div class="hidden">
                        Download
                        </div>
                    </a> -->
                </li>
            {/each}
            </ul>
        </section>
        {/if}

        <!-- <hr class="w-full border border-gray-200" /> -->

        <section class="event_presentation_list">


        <!-- {$lq__event_session_obj?.event_presentation_li?.length ?? 'loading...?'} -->

        {#if $lq__event_presentation_obj_li}

            <div class="text-xs"><strong>
                Presentations:
                {#if $ae_loc.administrator_access}
                    ({$lq__event_presentation_obj_li?.length})
                {/if}
            </strong></div>

            <!-- Maybe set max with? max-w-screen-md -->
            <ul class="event_presentation_list max-w-full space-y-2">
            {#each $lq__event_presentation_obj_li as event_presentation_obj}
                <li class="border-b-2 border-gray-300 my-1 py-1">

                    <!-- The presentation information -->
                    <div class="event_presentation_datetime_name flex flex-row justify-evenly gap-4">
                        <!-- <div class="event_presentation_datetime_name"> -->
                            {#if event_presentation_obj?.start_datetime}
                                <span class="event_presentation_datetime"><strong>{ae_util.iso_datetime_formatter(event_presentation_obj?.start_datetime, 'time_12_short_no_leading')}</strong></span>
                            {/if}

                            <span class="event_presentation_name grow">{event_presentation_obj?.name}</span>
                        <!-- </div> -->
                    </div>

                    <!-- The presenter list -->
                    {#if $lq__event_presenter_obj_li && $lq__event_presenter_obj_li.length}
                        <ul class="event_presentation_presenter_list">
                        {#each $lq__event_presenter_obj_li as event_presenter_obj, index}
                            {#if event_presenter_obj.event_presentation_id_random == event_presentation_obj.event_presentation_id_random}
                            <li>
                                <Launcher_presenter_view
                                    lq__event_presenter_obj={event_presenter_obj}
                                    />
                            </li>
                            {/if}
                        {/each}
                        </ul>
                    {:else}
                        <span class="event_launcher_no_presenters">No presenters to display</span>
                    {/if}

                </li>
            {/each}
            </ul>
        {:else}
            <p>No presentations available to display.</p>
        {/if}
        </section>
    {:else}
        <span class="fas fa-spinner fa-spin"></span>
        No session selected
    {/if}
</section>


<!-- {#if show_modal_upload_files}
<Element_modal_v3
        show = { true }
        modal_cover_body = { true }
        on:close={ () => {show_modal_upload_files=false;} }
        >

    <span slot="header_title">Upload New File(s)</span>

    <span slot="body">

        <Event_file_upload_form
            link_to_type={link_to_type}
            link_to_id={link_to_id}
            display_minimal={true}
            on:event_file_obj_li_updated={handle_event_file_obj_li_updated}
            />

    </span>
</Element_modal_v3>
{/if} -->


<style>
</style>
