<script lang="ts">
interface Props {
    data_url: any;
    lq__event_obj: any;
    lq__location_event_file_obj_li: any;
    // lq__event_location_obj: any;
    // export let lq__event_location_obj_li: any;
    lq__event_location_obj_li: any;
    // lq__event_session_obj: any;
    // export let lq__event_session_obj_li: any;
    lq__event_session_obj_li: any;
    log_lvl?: number;
}

let {
    data_url,
    lq__event_obj,
    lq__location_event_file_obj_li,
    // lq__event_location_obj,
    lq__event_location_obj_li,
    // lq__event_session_obj,
    lq__event_session_obj_li,
    log_lvl = $bindable(0),
}: Props = $props();

// *** Import Svelte specific
import { goto } from '$app/navigation';

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 Element_data_store from '$lib/element_data_store_v2.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/ae_events/db_events";
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';

import Menu_session_list_menu from './menu_session_list.svelte';


let slct_event_location_id: string = $state($events_slct.event_location_id);

$events_trigger = null;


let qry__enabled = 'enabled';
let qry__hidden = 'not_hidden';
if ($ae_loc.administrator_access) {
    qry__enabled = 'all';
    qry__hidden = 'all';
} else if ($ae_loc.trusted_access) {
    qry__enabled = 'enabled';
    qry__hidden = 'all';
} else {
    qry__enabled = 'enabled';
    qry__hidden = 'not_hidden';
}

let ae_promises: key_val = $state({
    get_li__event_file: null,
});

</script>


<section class="text-center space-y-1">

<h2 class="">{$lq__event_obj?.cfg_json.short_name ?? 'loading...'}</h2>

<button
    onclick={() => {
        $events_loc.launcher.show_content__hidden_files = !$events_loc.launcher.show_content__hidden_files;
    }}
    class="btn btn-sm preset-tonal-warning border border-warning-500 hover:preset-filled-primary-500 text-xs py-1 px-2"
    >
    {#if $events_loc.launcher.show_content__hidden_files}
        <span class="fas fa-eye-slash m-1"></span>
        Hide Files
    {:else}
        <span class="fas fa-eye m-1"></span>
        Hidden Files?
    {/if}

</button>
<button
    onclick={() => {
        $events_loc.launcher.show_content__hidden_sessions = !$events_loc.launcher.show_content__hidden_sessions;
    }}
    class="btn btn-sm preset-tonal-warning border border-warning-500 hover:preset-filled-primary-500 text-xs py-1 px-2"
    >
    {#if $events_loc.launcher.show_content__hidden_sessions}
        <span class="fas fa-eye-slash m-1"></span>
        Hide Sessions
    {:else}
        <span class="fas fa-eye m-1"></span>
        Hidden Sessions?
    {/if}
</button>

{#if $lq__event_location_obj_li && $lq__event_location_obj_li.length > 0}
<div class="text-xs"><strong>
    Locations:
    {#if $ae_loc.administrator_access}
        ({$lq__event_location_obj_li?.length})
    {/if}
    <!-- This should fade out once the data is loaded. -->
    {#await ae_promises[slct_event_location_id]}
        <span class="fas fa-spinner fa-spin text-blue-500"></span>
    {:then result}
        <span class="fas fa-check text-green-500"></span>
    {/await}
</strong></div>
<select
    class="select text-xs p-1"
    bind:value={slct_event_location_id}
    onchange={async () => {
        // console.log(`slct_event_location_id:`, slct_event_location_id);

        console.log('Remove fields from the URL.');
        // data_url.searchParams.delete('location_id');
        data_url.searchParams.delete('presentation_id');
        data_url.searchParams.delete('presenter_id');
        data_url.searchParams.delete('session_id');

        // let url_location_id = slct_event_location_id;
        // data_url.searchParams.set('location_id', url_location_id);

        let new_url = `/events/${$events_slct.event_id}/launcher`;

        if (slct_event_location_id) {
            $events_loc.launcher.slct.event_location_id = slct_event_location_id;
            $events_slct.event_location_id = slct_event_location_id;
            // console.log(`$events_loc.launcher.slct.event_location_id:`, $events_loc.launcher.slct.event_location_id);
            // data_url.searchParams.set('location_id', slct_event_location_id);
            // await tick();

            // $events_slct.event_location_id = slct_event_location_id;

            // dq__where_type_id_val = 'event_location_id';
            // dq__where_eq_id_val = slct_event_location_id;

            // $events_loc.launcher.slct.event_location_id = null;
            // await tick();
            // $events_loc.launcher.slct.event_location_id = slct_event_location_id;
            // await tick();

            // $slct.event_location_id = slct_event_location_id;
            // $slct_trigger = 'event_location_li';


            // $events_trigger = 'event_location_li';

            $events_slct.id_li__event_session = [];
            // await tick();
            ae_promises[slct_event_location_id] = events_func.load_ae_obj_li__event_session({
                api_cfg: $ae_api,
                for_obj_type: 'event_location',
                for_obj_id: $events_slct.event_location_id,
                inc_file_li: false,
                inc_presentation_li: false,
                enabled: 'enabled',
                hidden: 'all',
                limit: 49,
                try_cache: true,
                log_lvl: 1,
            })
            .then(async function (load_results) {
                console.log(`load_results = `, load_results);

                let event_session_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_session_obj = load_results[i];
                    let event_session_id_random = event_session_obj.event_session_id_random;
                    tmp_li.push(event_session_id_random);
                }
                event_session_id_li = tmp_li;
                console.log(`event_session_id_li:`, event_session_id_li);
                $events_slct.id_li__event_session = event_session_id_li;
                // $events_slct = {...$events_slct};
                // await tick();

                return load_results;
            })
            .finally(async () => {
                // This will hide the selected session if the location is changed to false.
                // WARNING: This may need to be commented out later.
                // $events_loc.launcher.slct.event_session_id = null;
                // await tick();
                // $events_loc.launcher.slct.event_session_id = event_session_obj?.id;
                // await tick();

                // $events_slct.event_session_id = event_session_obj?.id;
                // $events_slct.event_session_obj = event_session_obj;

                // ae_promises.slct_event_session_id = events_func.load_ae_obj_id__event_session({
                //     api_cfg: $ae_api,
                //     event_session_id: event_session_obj?.id,
                //     inc_file_li: true,
                //     inc_presentation_li: true,
                //     try_cache: true,
                //     log_lvl: 1
                // })
                // .then(async (load_results) => {
                //     console.log(`load_results = `, load_results);

                //     let new_url = data_url.toString();
                //     console.log(new_url);
                // events/UFu-gF-rZ-ws/launcher/XB6wmasQN6E?
                // let new_url = `/events/${$events_slct.event_id}/launcher/${$events_slct.event_location_id}`;
                // goto(new_url, {replaceState: true});
            });
            // let new_url = `/events/${$events_slct.event_id}/launcher/${$events_slct.event_location_id}`;
            // goto(new_url, {replaceState: true});
            // await tick();

            new_url = `/events/${$events_slct.event_id}/launcher/${$events_slct.event_location_id}`;

        } else {
            // This will hide the selected session if the location is changed to false.
            // WARNING: This may need to be commented out later.
            // slct_event_session_id = null;
            $events_loc.launcher.slct.event_location_id = null;
            $events_slct.event_location_id = null;
            $events_loc.launcher.slct.event_session_id = null;
            $events_slct.event_session_id = null;
            // WARNING: This may need to be commented out later.
        }
        // let new_url = `/events/${$events_slct.event_id}/launcher/${$events_slct.event_location_id}`;
        goto(new_url, {replaceState: true});
        // let new_url = data_url.toString()
        // console.log(new_url);
        // goto(new_url, {replaceState: false});
    }}
    >
    <option value="">Select a location</option>
    {#each $lq__event_location_obj_li as event_location_obj}
        <option
            value={event_location_obj?.id}
            >
        {event_location_obj?.name}
        </option>
    {/each}
</select>
{:else}
<p class="text-sm">
    No locations found.
    Event ID: {$lq__event_obj?.id}
</p>
{/if}

{#if $lq__location_event_file_obj_li}
{#each $lq__location_event_file_obj_li as event_file_obj, index}
    <button
        disabled={!$ae_loc.trusted_access}
        onclick={() => {
            // 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
            });
        }}
        class="btn btn-sm preset-tonal-primary border border-primary-500 hover:preset-filled-primary-500 text-xs py-1 px-2"
        >
        <span class="fas fa-file-archive m-1"></span>
        {event_file_obj?.filename}
    </button>
{/each}
{/if}

</section>


<section class="text-center">

{#if $lq__event_session_obj_li}
<Menu_session_list_menu
    data_url={data_url}
    lq__event_session_obj_li={lq__event_session_obj_li}
    />
{/if}

</section>

<!-- {/await} -->
