<script lang="ts">
export let data;
console.log(`ae_events_badges [slug] +page data:`, data);

import { onMount } from 'svelte';


// https://github.com/skeletonlabs/skeleton/blob/master/packages/skeleton/src/lib/utilities/Modal/types.ts
// To retrieve the store, getModalStore must be invoked at the top level of your component!
// import { getDrawerStore, getModalStore } from '@skeletonlabs/skeleton';
// import type {
//     DrawerSettings,
//     ModalSettings,
//     ModalComponent,
//     ModalStore
//     } from '@skeletonlabs/skeleton';
// const modalStore = getModalStore();

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import { events_func } from '$lib/ae_events_functions';
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';

let event_badge_li = liveQuery(
    () => db_events.badges.toArray()
);

// import Edit_modal_event_badge from '../10_edit_modal__event_badge_obj.svelte';

let ae_promises: key_val = {};
let load_obj_li_results: Promise<any>|key_val;

// Editing
// const modalComponentEditEventPresenterObj: ModalComponent = { ref: Edit_modal_event_badge, props: {container_class_li: 'w-full p-4 space-y-4 card'} };

// const modal_edit__event_badge: ModalSettings = {
// 	type: 'component',
// 	component: modalComponentEditEventPresenterObj,
//     title: 'Edit Badge Submission',
//     position: '', // default is "items-center"

//     response: (r: boolean | undefined) => handle_modal_close(r)
// };

// This function waits for the response from one of the modals. Do stuff when the modal is closed.
function handle_modal_close(response: boolean | undefined) {
    console.log('Modal closed. Response:', response);

    ae_util.handle_url_and_message('event_badge_id', null);

    // We want to keep these values in case they want to re-open the modal. Do NOT clear.
    // $events_slct.event_badge_id = null;
    // $events_slct.event_badge_obj = null;
}

if ($events_trigger == 'msg_parent' && $events_slct.event_id) {
    console.log(`Message parent with event_id ${$events_slct.event_id}`);
    $events_trigger = null

    let message = {'event_id': $events_slct.event_id};
    window.parent.postMessage(message, "*");
    // console.log('Message sent to parent (iframe):', message);
}


$ae_loc.hostname = data.url.hostname;
$ae_loc.site_domain = data.url.origin;

// We don't want the edit or view to show up by default. Maybe if we see an object ID param in the URL, we can show a modal.
$events_loc.show_edit__event_badge_obj = false;
$events_loc.show_view__event_badge_obj = false;

let ae_event_badge_get_promise: Promise<any>;
let ae_event_obj_get_promise;

// Load the AE Obj with ID based on the URL param.
if (data.url.searchParams.get('event_id')) {
    console.log(`Got an event_id: ${data.url.searchParams.get('event_id')}`);
    $events_slct.event_id = data.url.searchParams.get('event_id');
}

if ($events_slct.event_id) {
    console.log('Selected Event ID:', $events_slct.event_id);
    $events_trigger = 'load__event_badge_obj_li';
    // $events_trigger = 'load__event_obj';
}


onMount(() => {
    console.log('Events Badges [New/Edit]: +page.svelte');

    // console.log(`$ae_loc = `, $ae_loc);

	let url = window.location.href;
	// console.log(url);

    $ae_loc.href_url = url;
    // console.log(`$ae_loc.href_url = `, $ae_loc.href_url);

    // ae_util.handle_url_and_message('event_badge_id', $events_slct.event_badge_id);
    // if ($events_slct.event_badge_id) {
    //     console.log(`Got an ID. Let's show the modal!`);
    //     modalStore.trigger(modal_edit__event_badge);
    // } else {
    //     console.log(`No ID. Nothing to show.`);
    // }
});
// console.log(`$ae_loc = `, $ae_loc);
// $ae_loc.href_url = url;
// console.log(`$ae_loc.href_url = `, $ae_loc.href_url);






$: if ($events_trigger == 'load__event_obj' && $events_slct.event_id) {
    console.log('Selected Event ID:', $events_slct.event_id);

    $events_trigger = null;

    handle_load_ae_obj_id__event({event_id: $events_slct.event_id, try_cache: false});
}

async function handle_load_ae_obj_id__event({event_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__event() *** event_id=${event_id}`);

    let params = {};

	// $events_sess.status_load__event_id = 'loading';
    ae_event_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event',
        obj_id: event_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (event_obj_get_result) {
        if (event_obj_get_result) {
            $events_slct.event_obj = event_obj_get_result;
            console.log(`event object:`, $events_slct.event_obj);
        }

        // Auto show the selected event_badge ID
        // Is this pushState needed here?
        // Set the URL param "event_id" to the current event_badge ID.
        // const url = new URL(location);
        // url.searchParams.set('event_id', $events_slct.event_id);
        // history.pushState({}, '', url);

        // Is this postMessage needed here?
        // let message = {'event_id': $events_slct.event_id};
        // window.parent.postMessage(message, "*");

        // modalStore.trigger(modal_view__event_obj);
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_event_obj_get_promise;
}


// Load the Event Presenter Obj with ID based on the URL param.
// $events_slct.event_badge_id = data.url.searchParams.get('ae_id');
$events_slct.event_badge_id = data.url.searchParams.get('event_badge_id');
if ($events_slct.event_badge_id) {
    console.log('Selected Event Presenter ID:', $events_slct.event_badge_id);
    $events_trigger = 'load__event_badge';

    // $events_loc.show_edit__event_badge_obj = true;
    // $events_trigger = 'show_edit__event_badge';
}


$: if ($events_trigger == 'load__event_badge' && $events_slct.event_badge_id) {
    console.log('Selected Event Presenter ID:', $events_slct.event_badge_id);

    $events_trigger = null;

    handle_load_ae_obj_id__event_badge({event_badge_id: $events_slct.event_badge_id, try_cache: false});

    // modalStore.trigger(modal_edit__event_badge);
    // $events_trigger = 'show_edit__event_badge';
}

async function handle_load_ae_obj_id__event_badge({event_badge_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__event_badge() *** event_badge_id=${event_badge_id}`);

    let params = {};

	// $ae_loc.hub.event_badge_id_status_qry__search = 'loading';
    ae_event_badge_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event_badge',
        obj_id: event_badge_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (event_badge_get_result) {
        if (event_badge_get_result) {
            $events_slct.event_badge_obj = event_badge_get_result;
            console.log(`event_badge object:`, $events_slct.event_badge);
        }

        // Auto show the selected event_badge ID
        // Is this pushState needed here?
        // Set the URL param "event_badge_id" to the current event_badge ID.
        // const url = new URL(location);
        // url.searchParams.set('event_badge_id', $events_slct.event_badge_id);
        // history.pushState({}, '', url);

        // Is this postMessage needed here?
        // let message = {'event_badge_id': $events_slct.event_badge_id};
        // window.parent.postMessage(message, "*");
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_event_badge_get_promise;
}


// Updated 2024-03-06 late
$: if ($events_trigger == 'load__event_badge_obj_li' && $events_slct.event_id) {
    console.log(`handle_load_ae_obj_id__event() $events_slct.event_id=${$events_slct.event_id} api_cfg=`, $ae_api);

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

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

            load_obj_li_results = events_func.handle_load_ae_obj_li__badge({api_cfg: $ae_api, event_id: $events_slct.event_id, try_cache: false})
            .then(function (load_results) {
                if (load_results) {
                    console.log(`load_results=`, load_results);
                } else {
                    console.log('No results returned.');
                }
                // return load_results;
                console.log(`load_results=`, load_results);
                // $events_slct.badge_obj_li = load_results;
                return load_results;
            });
        }, 250);
    } else {
        console.log('*** $events_sess.status_qry__search != loading ***');
        $events_trigger = null;

        load_obj_li_results = events_func.handle_load_ae_obj_li__badge({api_cfg: $ae_api, event_id: $events_slct.event_id, try_cache: false})
        .then(function (load_results) {
            if (load_results) {
                console.log(`load_results=`, load_results);
            } else {
                console.log('No results returned.');
            }
            // return load_results;
            console.log(`load_results=`, load_results);
            // $events_slct.badge_obj_li = load_results;
            return load_results;
        });
    }
}

// Updated 2024-03-06
async function handle_load_ae_obj_li__badge({api_cfg: ae_api, event_id, try_cache=true}) {
    console.log(`*** handle_load_ae_obj_li__badge() *** event_id=${event_id}`);

    let fulltext_search_qry_str = $events_sess.badges.fulltext_search_qry_str;

    let enabled = $events_loc.qry_enabled;
    let hidden = $events_loc.qry__hidden;
    let limit = $events_loc.qry__limit;
    let offset = $events_loc.qry__offset;

    if ($ae_loc.administrator_access) {
        enabled = 'all';
        hidden = 'all';
        limit = 500;
    } else if ($ae_loc.trusted_access) {
        // enabled = 'all';
        hidden = 'all';
        limit = 50;
    }

    let params = {};

    let params_json: key_val = {};
    if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
        params_json['ft_qry'] = {
            'default_qry_str': fulltext_search_qry_str,
            // 'location_address_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
            // 'contact_li_json_ext': fulltext_search_qry_str, // JSON extracted text DB field
            };
    }

    // console.log('params_json:', params_json);
    // console.log(params_json);

    $events_sess.badges.status_qry__search = 'loading';
    ae_promises.load__event_badge_obj_li = await api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event_badge',
        for_obj_type: 'event',
        for_obj_id: event_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        enabled: enabled,
        hidden: hidden,
        order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'updated_on': 'DESC', 'created_on': 'DESC'},
        // order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 0
        })

    .then(function (badge_obj_li_get_result) {
        // console.log('Badge list:', badge_obj_li_get_result);
        if (badge_obj_li_get_result) {
            // $slct.badge_obj_li = badge_obj_li_get_result;
            handle_db_save_ae_obj_li({obj_type: 'event_badge', obj_li: badge_obj_li_get_result});
            return badge_obj_li_get_result;
        } else {
            // $slct.badge_obj_li = [];
            return [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        $events_sess.badges.status_qry__search = 'done';

        // console.log('Badge list:', badge_obj_li_get_result);
        // return badge_obj_li_get_result;
    });

    console.log('ae_promises.load__event_badge_obj_li:', ae_promises.load__event_badge_obj_li);
    return ae_promises.load__event_badge_obj_li;
}

// This function will loop through the badge_obj_li and save each one to the DB.
function handle_db_save_ae_obj_li({obj_type, obj_li}) {
    console.log(`*** handle_db_save_ae_obj_li() ***`);

    if (obj_li && obj_li.length) {
        obj_li.forEach(async function (obj) {
            // console.log(`ae_obj ${obj_type}:`, obj);

            try {
                const id_random = await db_events.badges.put({
                    id_random: obj.event_badge_id_random,
                    full_name: obj.full_name,
                    full_name_override: obj.full_name_override,
                    email: obj.email,
                    email_override: obj.email_override,
                    affiliations: obj.affiliations,
                    affiliations_override: obj.affiliations_override,
                    badge_type: obj.badge_type,
                    badge_type_override: obj.badge_type_override,
                    badge_type_code: obj.badge_type_code,
                    badge_type_code_override: obj.badge_type_code_override,
                    external_event_id: obj.external_event_id,
                    external_id: obj.external_id,
                    external_person_id: obj.external_person_id,
                });
                // console.log(`Put obj with ID: ${obj.event_badge_id_random} or ${id_random}`);
            } catch (error) {
                let status = `Failed to put ${obj.event_badge_id_random}: ${error}`;
                console.log(status);
            }

            // const id_random = await db_events.badges.put(obj);
            // console.log(`Put obj with ID: ${obj.event_badge_id_random}`);
        });
    }
}

</script>


<section
    class="ae_events_badges_review md:container h-full mx-auto"
    >

{#if $ae_loc.ds.hub__page__events_badges__create_info_header}
{@html $ae_loc.ds.hub__page__events_badges__create_info_header}
{:else}
<header>
    <h1 class="h2">Badge Review - Search</h1>
</header>
{/if}

<!-- <section class="btn btn-group"> -->
<input
    type="search"
    placeholder="Search (name, email, affiliatons, etc.)"
    id="badge_fulltext_search_qry_str"
    name="fulltext_search_qry_str"
    bind:value={$events_sess.badges.fulltext_search_qry_str}
    class="input w-96"
    >

<button
    class="btn variant-ghost-primary w-48"
    on:click={() => {
        $events_trigger = 'load__event_badge_obj_li';
        // $events_trigger = $events_trigger;

        // handle_oninput_fulltext_search_qry_str();

        // handle_badge_search('event_id', null);
        // modalStore.trigger(modal_edit__event_badge);

        // $events_trigger = 'load__event_badge';

        // $events_loc.show_edit__event_badge_obj = true;

        // modalStore.trigger(modal_edit__event_badge);
    }}
    >
    <span class="fas fa-search mx-1"></span>
    Search
</button>

{#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.badge_obj_li && $events_slct.badge_obj_li.length} -->
{#if $event_badge_li}
<section class="ae_h_scrollfix">
<h2 class="h3">Results:</h2>
<table class="table">
<thead>
<tr>
    <th>Badge</th>
    <!-- The email should only be the first 3 chars and then @domain name. -->
    <th>Email</th>
    <th>Affiliations</th>
</tr>
</thead>
<tbody>
<!-- {#each $events_slct.badge_obj_li as badge_obj} -->
{#each $event_badge_li as badge_obj}
<tr>
<td>
    <button
        class="btn variant-ghost-secondary w-96"
        on:click={() => {
            ae_util.handle_url_and_message('event_badge_id', badge_obj.event_badge_id_random);
            // modalStore.trigger(modal_edit__event_badge);

            // $events_trigger = 'load__event_badge';
            // $events_trigger = 'show_edit__event_badge';
            // $events_loc.show_edit__event_badge_obj = true;
            // modalStore.trigger(modal_edit__event_badge);
        }}
        >
        <span class="fas fa-id-badge mx-1"></span>
        Badge: {badge_obj.full_name}
    </button>
</td>
<td>
    <!-- The email should only be the first 3 chars and then @domain name. -->
    <!-- Example: original: scott.idem@oneskyit.com obscured: sco...@oneskyit.com -->
    <span class="fas fa-envelope mx-1"></span>
    {badge_obj.email ? badge_obj.email.replace(/^(.{3}).*@/, '$1...@') : ''}
</td>
<td>
    <span class="fas fa-users mx-1"></span>
    {badge_obj.affiliations}
</td>
</tr>
{/each}
</tbody>
</table>
</section>
{:else}
    <div class="alert alert-info">
        No badges found.
    </div>
{/if}



{#if $ae_loc.ds.hub__page__events_badges__create_info}
{@html $ae_loc.ds.hub__page__events_badges__create_info}
{:else}
<section>
        <div class="alert alert-info">
            More information goes here.
        </div>
</section>
{/if}


</section>
