<script lang="ts">
/** @type {import('./$types').PageData} */
export let data: any;
// console.log(`ae_events_pres_mgmt event [slug] +page.svelte data:`, data);

import { onMount } from 'svelte';
import { goto, invalidate, pushState, replaceState } from '$app/navigation';

import { clipboard, FileDropzone, getModalStore, localStorageStore, ProgressRadial, RadioGroup, RadioItem, TabGroup, Tab, TabAnchor } from '@skeletonlabs/skeleton';

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import { liveQuery } from "dexie";
import { db_events } from "$lib/db_events";
import { ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
$slct.account_id = data.account_id;
console.log(`$slct.account_id = `, $slct.account_id);
let ae_acct = data[$slct.account_id];
console.log(`ae_acct = `, ae_acct);

$events_slct.event_id = ae_acct.slct.event_id;
$events_slct.event_obj = ae_acct.slct.event_obj;
$events_slct.event_session_obj_li = ae_acct.slct.event_session_obj_li;

// import Leads_add_scan from './leads_add_scan.svelte';
// import Sessions_list from './sessions_list.svelte';
// import Leads_manage from './leads_manage.svelte';
// import Leads_payment from './leads_payment.svelte';

// let param_slug_event_id = data.params.slug;

let event_obj = liveQuery(
    () => db_events.events.get($events_slct.event_id)
    // () => db_events.events.get(param_slug_event_id)
    // () => db_events.events.toArray()
    // () => db_events.events
    //     .where('id_random')
    //     .equals($events_slct.event_id)
    //     // .orderBy('name')
    //     // .offset(10).limit(5)
    //     .toArray()
);

let event_obj_v2 = db_events.events.get($events_slct.event_id);


let load_obj_li_results: Promise<any>|key_val;
let search_submit_results: Promise<any>|key_val;

// These will likely be used for patch/update triggers. Maybe delete?
let ae_triggers: key_val = {};

let ae_event_session_get_promise: Promise<any>;

// if (!$events_loc.leads.tab) {
//     $events_loc.leads.tab = {};
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }

// if (!$events_loc.leads.auth_exhibit_kv) {
//     $events_loc.leads.auth_exhibit_kv = {};
// }

// if ($events_loc.leads.auth_exhibit_kv && $events_loc.leads.auth_exhibit_kv[$events_slct.event_id]) {
//     console.log('Logged in using shared exhibit staff passcode.');

//     if ($events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key) {
//         console.log(`Using the license key: ${$events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key}`);
//     } else {
//         console.log('License key (email) not used.');
//         $events_loc.leads.tab[$events_slct.event_id] = 'start';
//     }
// } else {
//     console.log('Not logged in using shared exhibit staff passcode.');
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }


onMount(() => {
    console.log('Events Event [slug]: +page.svelte');

    if (!$events_slct.event_id) {
        console.log(`No ID! Nothing to show. Try setting the ID again.`);
        $events_slct.event_id = $events_slct.event_id;
    }

});


// Updated 2024-06-12 late
$: if ($events_trigger == 'load__event_session_obj_li' && $events_slct.event_id) {
    console.log(`load__event_session_obj_li() $events_slct.event_id=${$events_slct.event_id}`);

    $events_trigger = null;

    if (!$events_sess.pres_mgmt.fulltext_search_qry_str || $events_sess?.pres_mgmt.fulltext_search_qry_str.length <= 1 ) {
        $events_slct.session_obj_li = [];
        // $events_sess.pres_mgmt.fulltext_search_qry_str = '';
    } else {

    // let type_code = $events_sess.pres_mgmt.search_badge_type_code;

    let search_str = $events_sess.pres_mgmt.fulltext_search_qry_str.trim();
    let search_method = 'lk'; // 'ft', 'lk', 'eq'
    let ft_search_str_new = '';
    let lk_search_str_new = '';

    if (search_method == 'ft') {
        // Add quotes around the search string to make it an exact match.
        ft_search_str_new = `"${search_str}"`;
    } else if (search_method == 'lk') {
        // Add a wildcard to the search string to make it a like match.
        lk_search_str_new = search_str.trim().replace(',', ' ').replace(';', ' ').replace('  ', '%').replace(' ', '%');
        lk_search_str_new = `%${lk_search_str_new}%`;
    }
    console.log(`"${search_str}"`);

    let params = {
        'qry__enabled': 'enabled',
        'qry__hidden': 'not_hidden',
        'qry__limit': 35,
    }

    if ($ae_loc.administrator_access) {
        params['qry__enabled'] = 'all';
        params['qry__hidden'] = 'all';
        params['qry__limit'] = 150;
    } else if ($ae_loc.trusted_access) {
        params['qry__enabled'] = 'enabled';
        params['qry__hidden'] = 'all';
        params['qry__limit'] = 75;
    } else {
        params['qry__enabled'] = 'enabled';
        params['qry__hidden'] = 'not_hidden';
        params['qry__limit'] = 35;
    }

    if ($events_sess.status_qry__search == 'loading') {
        console.log('*** $events_sess.status_qry__search == loading ***');

        setTimeout(() => {
            console.log("Delayed for X second.");

            $events_sess.status_qry__search = 'loading';

            search_submit_results = events_func.handle_search__event_session({
                api_cfg: $ae_api,
                event_id: $events_slct.event_id,
                // type_code: type_code,
                fulltext_search_qry_str: ft_search_str_new,
                like_search_qry_str: lk_search_str_new,
                // external_event_id: $events_loc.pres_mgmt.default__external_registration_id,
                params: params,
                try_cache: false
            })
            .then(function (search_results) {
                $events_slct.session_obj_li = search_results;
                console.log(search_results);
                $events_sess.status_qry__search = 'done';
            });
        }, 250);
    } else {
        console.log('*** $events_sess.status_qry__search != loading ***');

        $events_sess.status_qry__search = 'loading';

        search_submit_results = events_func.handle_search__event_session({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            // type_code: type_code,
            fulltext_search_qry_str: ft_search_str_new,
            like_search_qry_str: lk_search_str_new,
            // external_event_id: $events_loc.pres_mgmt.default__external_registration_id,
            params: params,
            try_cache: false
        })
        .then(function (search_results) {
            $events_slct.session_obj_li = search_results;
            console.log(search_results);
            $events_sess.status_qry__search = 'done';
        });
    }

    } // end if search string is valid
}




</script>


<section
    class="ae_events_pres_mgmt_event md:container h-full mx-auto flex flex-col items-center space-y-2 pt-0 pb-8"
    >


{#if $events_slct.event_id && $event_obj}
<h2 class="h3 text-center">{$event_obj.name}</h2>
<h3 class="h4 text-center">Presentation Management Hub</h3>
{/if}

<div class="variant-ghost-success my-2 p-2 rounded-md flex flex-row items-center">

<form
    on:submit|preventDefault={() => {
        $events_trigger = 'load__event_session_obj_li';
    }}
    autocomplete="off"
    class="form flex-grow flex flex-row flex-wrap gap-1 justify-center items-center w-full"
    >

    <input
    type="search"
    placeholder="Search for a session"
    id="session_fulltext_search_qry_str"
    bind:value={$events_sess.pres_mgmt.fulltext_search_qry_str}
    class="input text-1xl hover:text-2xl font-bold font-mono w-80 transition-all"
    on:keyup={() => {
        if ($events_sess.pres_mgmt?.fulltext_search_qry_str && $events_sess.pres_mgmt.fulltext_search_qry_str.length >= 3) {
            $events_trigger = 'load__event_session_obj_li';
        }
    }}
    autofocus
    suggest="off"
    data-ignore="true"
    />

    <button
        type="submit"
        class="btn btn-lg variant-ghost-success hover:variant-filled-success text-2xl font-bold w-48 transition-all"
        on:click={() => {

        }}
        >
        {#if $events_sess.pres_mgmt.status_qry__search == 'loading'}
            <span class="fas fa-spinner fa-spin"></span>
        {:else }
            <!-- Nothing -->
        {/if}
        <span class="fas fa-search mx-1"></span>
        Search
    </button>
</form>

</div>





{#await load_obj_li_results}
    <span class="modal-loading">
        <span class="fas fa-spinner fa-spin"></span>
        <span class="loading-text">
            Loading...
        </span>
    </span>
{:then load_obj_li_results}
    {#if load_obj_li_results}
    <span class="fas fa-check text-green-500"></span>
    <span class="saved-text">
        Loaded
    </span>
    {/if}
{/await}


{#if $events_slct?.session_obj_li && $events_slct.session_obj_li.length > 0}
<section class="ae_h_scrollfix">
    <h2 class="h3">Results:</h2>
    <table class="table">
    <thead>
    <tr>
        <th>Session</th>
        <th>Date</th>
        <th>Start/End</th>
        <th>Location</th>
        <!-- <th>Actions</th> -->
    </tr>
</thead>
<tbody>
{#each $events_slct.session_obj_li as session_obj}
<tr>
    <td>
        <a
            href="/events_pres_mgmt/session/{session_obj.event_session_id_random}"
            class="btn btn-md variant-ghost-secondary hover:variant-filled-secondary w-full"
            >
            <span class="fas fa-eye mx-1"></span>
            <span class="grow">
            <strong>{session_obj.name}</strong>
            </span>
        </a>
    </td>
    <td>
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'dddd')}
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'date_long_month_day')}
        </span>
    <td>
        {#if session_obj.start_datetime}
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'time_short')}
        </span>
        &ndash;<wbr>
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.end_datetime,'time_short')}
        </span>
        {:else}
        -- not set --
        {/if}
    </td>
    <td>{session_obj.event_location_name ?? '-- not set --'}</td>
    <!-- <td>
        <a
            href="/events_pres_mgmt/session/{session_obj.event_session_id_random}"
            class="btn btn-md variant-ghost-secondary hover:variant-glass-secondary"
            >
            <span class="fas fa-eye mx-1"></span>
            View
        </a>
    </td> -->
</tr>
{/each}
</tbody>
</table>
</section>
{:else}
<p class="text-center text-2xl bg-gray-100 p-4 rounded-md">
    No results to show. Please use the search above to find your session.
</p>
{/if}

</section>


<style lang="postcss">
/* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
div.ae_quick_modal_container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    background-color: hsla(0, 0%, 0%, .5);
}

/* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
section.ae_quick_popover {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    background-color: hsla(0, 0%, 100%, .95);
    padding: 1rem;
    border-radius: .5rem;
    box-shadow: 0 0 1rem hsla(0, 0%, 0%, .5);

    min-height: 30%;
    min-width: 80%;
}
</style>
