<script lang="ts">
	console.log(`ae_events_leads exhibit [slug] leads_manage.svelte`);

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

	import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';

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

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

	$: event_exhibit_obj = liveQuery(() => db_events.exhibit.get($events_slct.exhibit_id));

	// Quickly reload the data for this AE object from the API/DB
	// WARNING: This is triggered with every change to the parent object: $events_slct. This needs to be dealt with here and in other locations.
	$: if ($events_slct.exhibit_id) {
		console.log(`Reloading exhibit object:`, $events_slct.exhibit_id);
		events_func.handle_load_ae_obj_id__exhibit({
			api_cfg: $ae_api,
			exhibit_id: $events_slct.exhibit_id
		});

		// $events_slct.exhibit_obj = $event_exhibit_obj;
	}

	// Updated 2022-04-22
	// export let get_event_exhibit_tracking_export = async function get_event_exhibit_tracking_export({event_exhibit_id, file_type='CSV', return_file=true, filename=null, auto_download=false, params={}, log_lvl=0}) {
	//     console.log('*** stores_event_api.js: get_event_exhibit_tracking_export() ***');

	//     const endpoint = `/event/exhibit/${event_exhibit_id}/tracking/export`;
	//     if (file_type == 'CSV' || file_type == 'Excel') {
	//         params['file_type'] = file_type;
	//     }
	//     params['return_file'] = true;

	//     let event_exhibit_tracking_export_file_get_promise = await api.get_object({api_cfg: $ae_api, endpoint: endpoint, params: params, return_blob: true, filename: filename, auto_download: auto_download, log_lvl: log_lvl});
	//     // console.log(event_exhibit_tracking_export_file_get_promise);
	//     return event_exhibit_tracking_export_file_get_promise;
	// }
</script>

<section
	class="tab__manage flex flex-col wrap justify-center items-center space-y-4 ae_h_scrollfix"
>
	<h2 class="h3">
		<!-- <span class="fas fa-download"></span> -->
		Login and License
	</h2>

	{#if $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id] && $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id].key}
		<div class="space-y-2">
			<p class="mb-4">
				<strong>
					{#if $event_exhibit_obj?.priority}
						<span class="fas fa-check text-green-500"></span> Leads license(s) marked as paid for this
						exhibit!
					{:else}
						The leads license have not been marked as paid yet. If you have already paid, please
						wait and this will be reflected here within 48 business hours.
					{/if}
				</strong>
			</p>

			<p>
				Exhibit name: <strong
					>{$events_slct.exhibit_obj.name} # {$events_slct.exhibit_obj.code}</strong
				>
			</p>

			<div class="space-y-2">
				<strong>Logged in and using license for:</strong>
				{#if $event_exhibit_obj?.license_li_json}
					<!-- <div class="flex flex-row wrap gap-1"> -->
					{#each $event_exhibit_obj?.license_li_json as license, index}
						{#if license.email === $events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id].key}
							<div class="flex flex-row items-center space-x-2">
								<span class="ae_label">Name:</span>
								<span class="ae_value">{license.full_name}</span>
							</div>
						{/if}
					{/each}
					<!-- </div> -->
				{/if}
				<div class="flex flex-row items-center space-x-2">
					<span class="ae_label">Email:</span>
					<span class="ae_value"
						>{$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id].key}
					</span>
				</div>
				<div class="flex flex-row items-center space-x-2">
					<span class="ae_label">Started:</span>
					<span class="ae_value"
						>{ae_util.iso_datetime_formatter(
							$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id].updated_on,
							'datetime_12_long'
						)}</span
					>
				</div>
			</div>

			<!-- Show the full_name of the person associated with that license key email address. The license information is stored in an array. The license key is not the index number value in the array. Ideally I was planning to make the key the email address, not an array index number. -->
			<button
				type="button"
				class="btn btn-sm preset-tonal-warning border border-warning-500 w-48"
				on:click={() => {
					$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id].key = null;
				}}
			>
				<span class="fas fa-times mx-1"></span>
				Clear License
			</button>

			<button
				type="button"
				on:click={() => {
					console.log('Log Out');
					$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id] = null;
				}}
				title="Log out"
				class="btn btn-sm preset-tonal-warning border border-warning-500 w-48"
			>
				<span class="fas fa-sign-out-alt mx-1"></span>
				Log Out
			</button>
		</div>
	{:else if $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id]}
		<div class="border border-slate-500/10 p-2 preset-tonal-warning">
			You are logged in using the shared passcode for the exhibit. You will want to select a license
			to fully use this lead retrieval service. Please go to the Main tab and select a license to
			use.
		</div>

		<button
			type="button"
			on:click={() => {
				console.log('Log Out');
				$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id] = null;
			}}
			title="Log out"
			class="btn btn-sm preset-tonal-warning border border-warning-500 w-48"
		>
			<span class="fas fa-sign-out-alt mx-1"></span>
			Log Out
		</button>
	{:else}
		<div class="border border-slate-500/10 p-2 preset-tonal-warning">
			Please go to the Main tab to login using the shared staff passcode for this exhibit. Then
			select a license to use.
		</div>
	{/if}

	<!-- Field for exhibit staff shared passcode reset -->
	<Element_ae_crud
		trigger_patch={ae_triggers.staff_passcode}
		api_cfg={$ae_api}
		object_type={'event_exhibit'}
		object_id={$event_exhibit_obj?.event_exhibit_id_random}
		field_name={'staff_passcode'}
		field_type={'text'}
		field_value={$events_slct.exhibit_obj.staff_passcode}
		allow_null={false}
		hide_edit_btn={true}
		outline_element={false}
		show_crud={false}
		display_inline={true}
		class_li={'m-1'}
		on:ae_crud_updated={(e) => {
			console.log(`ae_crud_updated event:`, e.detail);
			events_func.handle_load_ae_obj_id__exhibit({
				api_cfg: $ae_api,
				exhibit_id: $events_slct.exhibit_id
			});
		}}
	>
		Shared exhibit passcode:
		<span class="ae_value">{$events_slct.exhibit_obj.staff_passcode}</span>
		{#if $ae_loc.administrator_access}
			<input
				type="text"
				minlength="5"
				maxlength="32"
				bind:value={$events_slct.exhibit_obj.staff_passcode}
				class="input w-24 m-1"
			/>
			<button
				type="button"
				on:click={() => {
					// $events_slct.exhibit_obj.staff_passcode = '';
					ae_triggers.staff_passcode = true;
				}}
				disabled={$events_slct.exhibit_obj.staff_passcode.length < 5}
				class="btn btn-sm preset-tonal-warning"
			>
				<span class="fas fa-sync m-1"></span>
				Reset Passcode
			</button>
		{/if}
	</Element_ae_crud>

	<!-- {#if $ae_loc.administrator_access} -->
	<!-- Priority (paid) means this exhibit has paid for their license(s). They will also appear at the top of lists. -->
	<Element_ae_crud
		trigger_patch={ae_triggers.priority}
		api_cfg={$ae_api}
		object_type={'event_exhibit'}
		object_id={$event_exhibit_obj?.event_exhibit_id_random}
		field_name={'priority'}
		field_type={'button'}
		field_value={$events_slct.exhibit_obj.priority}
		allow_null={false}
		hide_edit_btn={true}
		outline_element={false}
		show_crud={false}
		display_inline={true}
		class_li={'m-1'}
		on:ae_crud_updated={(e) => {
			console.log(`ae_crud_updated event:`, e.detail);
			events_func.handle_load_ae_obj_id__exhibit({
				api_cfg: $ae_api,
				exhibit_id: $events_slct.exhibit_id
			});
		}}
	>
		{#if !$event_exhibit_obj?.priority}
			Not Paid:
			<span class="fas fa-question text-red-500 m-1"></span>
			<span class="fas fa-credit-card mx-1"></span>
			Waiting for payment
		{:else}
			Paid:
			<span class="fas fa-check text-green-500 m-1"></span>
			<span class="fas fa-credit-card mx-1"></span>
			Marked as paid
		{/if}

		{#if $ae_loc.administrator_access}
			<button
				type="button"
				on:click={() => {
					$events_slct.exhibit_obj.priority = !$event_exhibit_obj?.priority;
					ae_triggers.priority = true;
				}}
				class="btn btn-sm preset-tonal-warning"
			>
				{@html $event_exhibit_obj?.priority
					? '<span class="fas fa-sync m-1"></span> Not paid?'
					: '<span class="fa fa-sync m-1"></span> Mark as paid?'}
			</button>
		{/if}
	</Element_ae_crud>

	<!-- Give option show show or hide the Payment tab if they have been marked as paid (priority = true). -->
	<div>
		{#if $event_exhibit_obj?.priority}
			{#if $events_loc.leads.show_option__paid_tab}
				<button
					type="button"
					on:click={() => {
						$events_loc.leads.show_option__paid_tab = false;
					}}
					class="btn btn-sm preset-tonal-primary border border-primary-500"
				>
					<span class="fas fa-eye-slash m-1"></span>
					Hide Payment Tab
				</button>
			{:else}
				<button
					type="button"
					on:click={() => {
						$events_loc.leads.show_option__paid_tab = !$events_loc.leads.show_option__paid_tab;
					}}
					class="btn btn-sm preset-tonal-primary"
				>
					<span class="fas fa-eye m-1"></span>
					Show Hidden Payment Tab
				</button>
			{/if}
		{/if}
	</div>

	<!-- Field for license_max. A number between 0 and 10. -->
	<Element_ae_crud
		trigger_patch={ae_triggers.license_max}
		api_cfg={$ae_api}
		object_type={'event_exhibit'}
		object_id={$event_exhibit_obj?.event_exhibit_id_random}
		field_name={'license_max'}
		field_type={'text'}
		field_value={$events_slct.exhibit_obj.license_max}
		allow_null={false}
		hide_edit_btn={true}
		outline_element={false}
		show_crud={false}
		display_inline={true}
		class_li={'m-1'}
		on:ae_crud_updated={(e) => {
			console.log(`ae_crud_updated event:`, e.detail);
			events_func.handle_load_ae_obj_id__exhibit({
				api_cfg: $ae_api,
				exhibit_id: $events_slct.exhibit_id
			});
		}}
	>
		Max licenses:
		{#if $events_slct.exhibit_obj?.license_max}
			<span class="fas fa-users m-1"></span> {$events_slct.exhibit_obj.license_max}
		{:else}
			<span class="fas fa-users m-1"></span> 0
		{/if}
		{#if $ae_loc.administrator_access}
			<input
				type="number"
				min="0"
				max="10"
				step="1"
				bind:value={$events_slct.exhibit_obj.license_max}
				class="input w-16 m-1"
			/>
			<button
				type="button"
				on:click={() => {
					// $events_slct.exhibit_obj.license_max = 0;
					ae_triggers.license_max = true;
				}}
				class="btn btn-sm preset-tonal-warning"
			>
				<span class="fas fa-save m-1"></span>
				Save
			</button>
		{/if}
	</Element_ae_crud>

	<!-- Field for leads_device_sm_qty. A number between 0 and 10. -->
	<Element_ae_crud
		trigger_patch={ae_triggers.leads_device_sm_qty}
		api_cfg={$ae_api}
		object_type={'event_exhibit'}
		object_id={$event_exhibit_obj?.event_exhibit_id_random}
		field_name={'leads_device_sm_qty'}
		field_type={'text'}
		field_value={$events_slct.exhibit_obj.leads_device_sm_qty}
		allow_null={false}
		hide_edit_btn={true}
		outline_element={false}
		show_crud={false}
		display_inline={true}
		class_li={'m-1'}
		on:ae_crud_updated={(e) => {
			console.log(`ae_crud_updated event:`, e.detail);
			events_func.handle_load_ae_obj_id__exhibit({
				api_cfg: $ae_api,
				exhibit_id: $events_slct.exhibit_id
			});
		}}
	>
		Small devices:
		{#if $events_slct.exhibit_obj?.leads_device_sm_qty}
			<span class="fas fa-mobile-alt m-1"></span> {$events_slct.exhibit_obj.leads_device_sm_qty}
		{:else}
			<span class="fas fa-mobile-alt m-1"></span> 0
		{/if}
		{#if $ae_loc.administrator_access}
			<input
				type="number"
				min="0"
				max="10"
				step="1"
				bind:value={$events_slct.exhibit_obj.leads_device_sm_qty}
				class="input w-16 m-1"
			/>
			<button
				type="button"
				on:click={() => {
					// $events_slct.exhibit_obj.leads_device_sm_qty = 0;
					ae_triggers.leads_device_sm_qty = true;
				}}
				class="btn btn-sm preset-tonal-warning"
			>
				<span class="fas fa-save m-1"></span>
				Save
			</button>
		{/if}
	</Element_ae_crud>

	<!-- Field for leads_device_lg_qty. A number between 0 and 10. -->
	<Element_ae_crud
		trigger_patch={ae_triggers.leads_device_lg_qty}
		api_cfg={$ae_api}
		object_type={'event_exhibit'}
		object_id={$event_exhibit_obj?.event_exhibit_id_random}
		field_name={'leads_device_lg_qty'}
		field_type={'text'}
		field_value={$events_slct.exhibit_obj.leads_device_lg_qty}
		allow_null={false}
		hide_edit_btn={true}
		outline_element={false}
		show_crud={false}
		display_inline={true}
		class_li={'m-1'}
		on:ae_crud_updated={(e) => {
			console.log(`ae_crud_updated event:`, e.detail);
			events_func.handle_load_ae_obj_id__exhibit({
				api_cfg: $ae_api,
				exhibit_id: $events_slct.exhibit_id
			});
		}}
	>
		Large devices:
		{#if $events_slct.exhibit_obj?.leads_device_lg_qty}
			<span class="fas fa-tablet-alt m-1"></span> {$events_slct.exhibit_obj.leads_device_lg_qty}
		{:else}
			<span class="fas fa-tablet-alt m-1"></span> 0
		{/if}
		{#if $ae_loc.administrator_access}
			<input
				type="number"
				min="0"
				max="10"
				step="1"
				bind:value={$events_slct.exhibit_obj.leads_device_lg_qty}
				class="input w-16 m-1"
			/>
			<button
				type="button"
				on:click={() => {
					// $events_slct.exhibit_obj.leads_device_lg_qty = 0;
					ae_triggers.leads_device_lg_qty = true;
				}}
				class="btn btn-sm preset-tonal-warning"
			>
				<span class="fas fa-save m-1"></span>
				Save
			</button>
		{/if}
	</Element_ae_crud>

	<!-- {/if} -->

	{#if $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id] && $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id].key}
		<hr class="border w-full" />

		<h2 class="h3">
			<!-- <span class="fas fa-download"></span> -->
			Export Data
		</h2>

		<p class="border border-slate-500/10 p-2 preset-tonal-secondary">
			Use this to export the leads data for this exhibit to an Excel file format. The data can be
			downloaded at anytime using the export button below. The data exported to exhibitors will
			likely be these fields: given/first name, family/last name, professional title, affiliations,
			email, city, state/province, country. The exact fields exported sometimes changes slightly
			from meeting to meeting.
		</p>
		<button
			type="button"
			on:click={() => {
				if (!confirm('Download data exported to an Excel file?')) {
					return false;
				}
				ae_promises.download__exhibit_tracking_export =
					events_func.handle_download_export__event_exhibit_tracking({
						api_cfg: $ae_api,
						exhibit_id: $events_slct.exhibit_id,
						file_type: 'Excel',
						return_file: true,
						filename: `lead_retrieval_export_${$events_slct.exhibit_obj.name.replaceAll(' ', '_')}.xlsx`,
						auto_download: true,
						log_lvl: 2
					});

				// get_event_exhibit_tracking_export({ 'event_exhibit_id': $events_slct.exhibit_id, file_type: 'Excel', 'return_file': true, filename: `lead_retrieval_export_${$events_slct.exhibit_obj.name.replaceAll(' ', '_')}.xlsx`, auto_download: true, log_lvl: 2 });
				// .replace(' ', '_')
			}}
			disabled={!$events_slct.exhibit_obj.priority}
			class="btn btn-sm preset-tonal-primary border border-primary-500 w-48 mb-1 export_data_btn"
			title={`Download leads data for ${$events_slct.exhibit_obj.name}`}
		>
			{#await ae_promises.download__exhibit_tracking_export}
				<span class="fas fa-spinner fa-spin"></span>
				<!-- <span class="loading-text">
        Downloading...
    </span> -->
			{:then}
				<!-- Done? -->
			{/await}
			<span class="fas fa-download mx-1"></span> Export Data
		</button>
	{/if}
	<!-- $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id].key -->

	<hr class="border w-full" />

	<h2 class="h3">
		<!-- <span class="fas fa-cogs"></span> -->
		Additional Settings
	</h2>

	<div>
		List refresh interval in seconds:
		<select
			bind:value={$events_loc.leads.refresh_interval__tracking_li}
			on:change={() => {
				console.log(
					'List refresh interval in seconds:',
					$events_loc.leads.refresh_interval__tracking_li
				);
				// clearInterval($events_loc.leads.refresh_interval_id);
				// $events_loc.leads.refresh_interval_id = setInterval(() => {
				//     console.log('Refreshing list...');
				//     events_func.handle_load_ae_obj_id__exhibit({api_cfg: $ae_api, exhibit_id: $events_slct.exhibit_id});
				// }, $events_loc.leads.refresh_interval);
			}}
			class="input w-36 m-1"
		>
			{#if $ae_loc.trusted_access}
				<option value={1000}>1 seconds</option>
				<option value={3000}>3 seconds</option>
				<option value={5000}>5 seconds</option>
				<option value={7000}>7 seconds</option>
			{/if}
			<option value={10000}>10 seconds</option>
			<option value={15000}>15 seconds</option>
			<option value={25000}>25 seconds</option>
			<option value={30000}>30 seconds</option>
			<option value={45000}>45 seconds</option>
			<option value={60000}>1 minute</option>
			<option value={120000}>2 minutes</option>
		</select>
	</div>

	<div class="text-center">
		<button
			class="btn btn-sm preset-tonal-warning border border-warning-500 m-1"
			title="Reload and clear the page file cache"
			on:click={() => {
				// $ae_loc.
				window.location.reload(true);
			}}
		>
			<span class="fas fa-sync m-1"></span>
			Reload Without Cache
		</button>
		<button
			class="btn btn-sm preset-tonal-warning border border-warning-500 m-1"
			title="Clear the browser storage for this page"
			on:click={() => {
				// $ae_loc.
				localStorage.clear();
				sessionStorage.clear();
				alert(
					'Local and Session Storage cleared. You will probably want to reload/refresh the page as well.'
				);
			}}
		>
			<span class="fas fa-eraser m-1"></span>
			Clear Storage
		</button>

		<button
			class="btn btn-sm preset-tonal-warning border border-warning-500 m-1"
			title="Clear browser iDB storage"
			on:click={() => {
				db_events.delete().then(() => {
					alert(
						'IndexedDB storage cleared. You will probably want to reload/refresh the page as well.'
					);
				});
			}}
		>
			<span class="fas fa-database m-1"></span>
			Clear iDB
		</button>
	</div>

	{#if $events_loc?.leads.auth_exhibit_kv[$events_slct.exhibit_id]}
		<div class="">
			Auto hide header/footer on sign in:
			<button
				type="button"
				on:click={() => {
					console.log('Auto hide on sign in');
					$events_loc.leads.auto_hide_on_sign_in = !$events_loc.leads.auto_hide_on_sign_in;
				}}
				class="btn btn-sm preset-tonal w-48"
			>
				<span class="fas fa-eye-slash mx-1"></span>
				Turn {$events_loc.leads.auto_hide_on_sign_in ? 'off' : 'on'} auto hide
			</button>
		</div>

		<div>
			Turn on iframe mode:
			<button
				type="button"
				on:click={() => {
					console.log('Turn on iframe mode');
					$ae_loc.iframe = !$ae_loc.iframe;
				}}
				class="btn btn-sm preset-tonal w-48"
			>
				<span class="fas fa-compress mx-1"></span>
				Turn {$ae_loc.iframe ? 'off' : 'on'} iframe mode
			</button>
		</div>

		<div>
			Show or hide additional details:
			<button
				type="button"
				on:click={() => {
					console.log('Show/Hide Details');
					$events_loc.show_details = !$events_loc.show_details;
				}}
				class="btn btn-sm preset-tonal w-48"
			>
				<span class="fas fa-eye mx-1"></span>
				Show/Hide Details
			</button>
		</div>

		<!-- {#if $events_loc?.leads.auth_exhibit_kv && $events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id]}
    <button
        type="button"
        on:click={() => {
            console.log('Log Out');
            $events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id] = null;
        }}
        title="Log out"
        class="btn variant-ghost-primary w-48"
        >
        <span class="fas fa-sign-out-alt mx-1"></span>
        Log Out
    </button>
    <p>To use the lead retrieval service, please select a license from the list on the Main tab.</p>
    {/if} -->
	{:else}
		<div>You must be logged in to view this tab.</div>
	{/if}
	<!-- $events_loc?.leads.auth_exhibit_kv && $events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id] -->
</section>
