<script lang="ts">
	interface Props {
		// Exports
		container_class_li?: string | Array<string>;
		// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
		use_id_li?: boolean;
		event_badge_id_li?: Array<string>;
		qry_idb?: boolean;
		qry_str?: string;
		qry_type_code?: string;
		// event_badge_obj_li?: Array<any>;
		link_to_type?: string;
		link_to_id?: string;
		// export let lq__event_presentation_obj
		log_lvl?: number;
		show_sensitive_fields?: boolean;
		hide_affiliations?: boolean;
		hide_location?: boolean;
		hide_badge_type?: boolean;
	}

	let {
		container_class_li = [],
		use_id_li = $bindable(true),
		event_badge_id_li = $bindable([]),
		qry_idb = false,
		qry_str = '',
		qry_type_code = '',
		// event_badge_obj_li = $bindable(),
		link_to_type,
		link_to_id,
		log_lvl = $bindable(0),
		show_sensitive_fields = true,
		hide_affiliations = false,
		hide_location = false,
		hide_badge_type = false
	}: Props = $props();

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

	// *** Import other supporting libraries
	import { liveQuery } from 'dexie';

	// *** Import Aether specific variables and functions
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';

	import {
		events_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';
	import { db_events } from '$lib/ae_events/db_events';

	if (log_lvl) {
		if (link_to_type && link_to_id) {
			console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`);
		} else {
			console.log(`No link_to_type or link_to_id defined.`);
		}
	}

	// Variables
	// let ae_promises: key_val = {};
	// let ae_tmp: key_val = {};
	// let ae_triggers: key_val = {};

	// let event_badge_id_li: Array<string> = $state([]);

	// *** Functions and Logic
	let lq__event_badge_obj_li = $derived(
		liveQuery(async () => {
			let results: any;
			log_lvl = 1;

			if (use_id_li && event_badge_id_li?.length) {
				if (log_lvl) {
					console.log(`LQ - Using event_badge_id_li to get event badges.`, event_badge_id_li);
				}

				results = await db_events.badge.bulkGet(event_badge_id_li);
			} else if (qry_str && qry_str?.length) {
				if (log_lvl) {
					console.log(`LQ - Using qry_str to get event badges. qry_str=${qry_str}`);
				}

				// let ft_query = ae_util.sanitize_fulltext_search(qry_str);
				// let ft_query = qry_str;
				if (log_lvl) {
					console.log(`Fulltext search query: ${qry_str}`);
				}

				if (qry_type_code && qry_type_code !== 'all') {
					if (log_lvl) {
						console.log(`Also filtering by badge type code: ${qry_type_code}`);
					}
					results = await db_events.badge
						.where('default_qry_string')
						.equalsIgnoreCase(qry_str)
						// .equals(ft_query)
						// .and((badge) => badge.badge_type_code === qry_type_code && badge.event_id === $events_slct.event_id)
						.sortBy('tmp_sort_2');
				} else {
					// .matches(/testing/i).toArray()
					// .matches(/middle_text/i).toArray()

					results = await db_events.badge
						.where('full_name')
						.startsWithIgnoreCase(qry_str)
						// .startsWithIgnoreCase(qry_str)
						// .where('default_qry_string')
						// .equalsIgnoreCase(qry_str)
						// .equals(ft_query)
						// .and((badge) => badge.event_id === $events_slct.event_id)
						.sortBy('tmp_sort_2');
				}

				// event_badge_id_li = results.map((badge) => badge.event_badge_id);

				// } else if (event_badge_obj_li?.length) {
				//     if (log_lvl) {
				//         console.log(`LQ - Using event_badge_obj_li to get event badges.`);
				//     }

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

				//     for (let i = 0; i < event_badge_obj_li.length; i++) {
				//         let event_badge_obj = event_badge_obj_li[i];
				//         let event_badge_id_random = event_badge_obj.event_badge_id_random;
				//         event_badge_id_li.push(event_badge_id_random);
				//     }

				//     results = await db_events.badge
				//         .bulkGet(event_badge_id_li);
			} else if (link_to_type && link_to_id) {
				let dq__where_type_id_val: string = `${link_to_type}_id_random`;
				let dq__where_eq_id_val: string = link_to_id ?? '';

				if (log_lvl) {
					console.log(
						`LQ - Trying where: ${dq__where_type_id_val}; equals: ${dq__where_eq_id_val}`
					);
				}
				// event_badge_id_li = [];
				results = await db_events.badge
					.where(dq__where_type_id_val)
					.equals(dq__where_eq_id_val)
					.sortBy('tmp_sort_2');

				// event_badge_id_li = results.map((badge) => badge.event_badge_id);

				// } else {
				//     event_badge_id_li = [];
				//     results = [];
			}

			// log_lvl = 1;
			// Check if results are different than the current badge version stored under $events_slct
			if (
				$events_slct.event_badge_obj_li &&
				JSON.stringify($events_slct.event_badge_obj_li) !== JSON.stringify(results)
			) {
				$events_slct.event_badge_obj_li = [...results];
				if (log_lvl) {
					console.log(
						`Session slct li stored version has changed for ID = ${$events_slct.event_id}`,
						$events_slct.event_badge_obj_li
					);
				}
			} else if (!$events_slct?.event_badge_obj_li) {
				$events_slct.event_badge_obj_li = [...results];
				if (log_lvl) {
					console.log(
						`Session slct li stored version was not set for ID = ${$events_slct.event_id}`,
						$events_slct.event_badge_obj_li
					);
				}
			} else {
				if (log_lvl > 1) {
					console.log(
						`Session slct li stored version has not changed for ID = ${$events_slct.event_id}`,
						$events_slct.event_badge_obj_li
					);
				}
			}

			return results;

			// if (event_badge_id_li.length) {
			//     let results = await db_events.badge
			//         .bulkGet(event_badge_id_li);

			//     return results;
			// } else if (link_to_type && link_to_id) {
			//     console.log(`Trying where: ${dq__where_type_id_val}; equals: ${dq__where_eq_id_val}`);
			//     let results = await db_events.badge
			//         .where(dq__where_type_id_val)
			//         .equals(dq__where_eq_id_val)
			//         .sortBy('name')

			//     return results;
			// } else {
			//     return null;
			// }
		})
	);
</script>

<section class="px-1 flex flex-col gap-1 items-center justify-center space-y-1">
	<!-- event_badge_id_li?.length &&  -->
	{#if $lq__event_badge_obj_li?.length}
		<header class="w-full flex flex-row gap-1 items-center justify-start">
			<h2 class="text-base">Results:</h2>
			<div class="text-3xl font-bold preset-filled-success-100-900 px-4 rounded-lg">
				<span class="fas fa-list-ol mx-4"></span>
				{$lq__event_badge_obj_li.length}&times;
			</div>
		</header>

		<!-- The email should only be the first 3 chars and then @domain name. -->

		<ul class="list-disc list-inside">
			{#each $lq__event_badge_obj_li as event_badge_obj (event_badge_obj.event_badge_id_random)}
				<li
					class="
                border-b border-gray-300 dark:border-gray-600 py-0.5
                flex flex-row gap-1 items-center justify-between w-full
                "
				>
					<a
						href={`/events/${event_badge_obj.event_id}/badges/${event_badge_obj.event_badge_id}`}
						class="flex flex-row gap-1 items-center justify-start min-w-fit"
						title={`Badge: ${event_badge_obj.full_name ?? event_badge_obj.given_name ?? '-- no name --'}\nID: ${event_badge_obj.event_badge_id}`}
					>
						<span>
							{#if event_badge_obj.hide}
								<span class="fas fa-eye-slash mx-1"></span>
							{:else}
								<span class="fas fa-id-badge mx-1"></span>
							{/if}
							{#if event_badge_obj.print_count >= 1}
								<!-- Show a green checkmark -->
								<span class="fas fa-check text-green-500"></span>

								{#if $ae_loc.trusted_access}
									<span class="print_count preset-tonal-warning px-1"
										>{event_badge_obj.print_count}×</span
									>
								{/if}
							{/if}
						</span>

						<span class="font-bold">
							{#if event_badge_obj.full_name_override}
								{event_badge_obj.full_name_override}
							{:else if event_badge_obj.full_name}
								{event_badge_obj.full_name}
							{:else if event_badge_obj.given_name}
								{event_badge_obj.given_name} {event_badge_obj.family_name}
							{:else}
								-- no name --
							{/if}
						</span>
					</a>

					{#if show_sensitive_fields}
						-
						<span class="min-w-fit">
							<!-- 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"></span>
							{event_badge_obj.email ? event_badge_obj.email.replace(/^(.{3}).*@/, '$1...@') : ''}
						</span>
					{/if}
					{#if !hide_affiliations}
						-
						{event_badge_obj?.affiliations ?? '-- no affiliations --'}
					{/if}
					{#if !hide_location}
						-
						{event_badge_obj?.location ?? '-- no location --'}
					{/if}
					{#if !hide_badge_type}
						-
						<span class="italic">{event_badge_obj?.badge_type}</span>
					{/if}
				</li>
			{/each}
		</ul>

		<!-- <table class="table">
        <thead>
        <tr>
            <th>Badge</th>
            <th>Email / Affiliations / Location</th>
            <th>Affiliations / Location</th>
            <th>Badge Type</th>
        </tr>
        </thead>
        <tbody>
            <tr><td class=""></td><td class=""></td></tr>
        </tbody>
    </table> -->
	{:else}
		<div class="">
			<p>No results available to show.</p>
		</div>
	{/if}
</section>
