<script lang="ts">
	/** @type {import('./$types').PageData} */
	let log_lvl: number = $state(1);

	interface Props {
		data: any;
	}

	let { data }: Props = $props();

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

	// *** Import other supporting libraries
	// import {
	//     ArrowDown01, ArrowDown10, ArrowDownUp,
	//     BetweenVerticalEnd, BetweenVerticalStart,
	//     BookHeart, BookImage, Bookmark, BookOpenText, BriefcaseBusiness,
	//     Check, Copy,
	//     Expand, Eye, EyeOff,
	//     Flag, FlagOff, FilePlus, Fingerprint,
	//     Globe,
	//     Library,
	//     MessageSquareWarning, Minus,
	//     Notebook,
	//     Pencil, Plus,
	//     RemoveFormatting,
	//     SquareLibrary,
	//     Shapes, Share2, ShieldCheck, ShieldMinus, Siren, Skull,
	//     Tags, Target, ToggleLeft, ToggleRight, Trash2, TypeOutline,
	//     X
	// } from '@lucide/svelte';
	// import * as icons from '@lucide/svelte';
	// import { Modal } from 'flowbite-svelte';
	import { liveQuery } from 'dexie';

	// *** Import Aether specific variables and functions
	// import type { key_val } from '$lib/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	// import { core_func } from '$lib/ae_core/ae_core_functions';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import { db_journals } from '$lib/ae_journals/db_journals';
	import {
		journals_loc,
		journals_sess,
		journals_slct,
		journals_prom,
		journals_trig
	} from '$lib/ae_journals/ae_journals_stores';
	import { journals_func } from '$lib/ae_journals/ae_journals_functions';

	// import Journal_obj_id_edit from './ae_journals_comp__journal_obj_id_edit.svelte';
	import Journal_view from './../ae_comp__journal_obj_id_view.svelte';
	// import Journal_page_menu from './session_page_menu.svelte';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';

	import Journal_entry_obj_li from './../ae_comp__journal_entry_obj_li.svelte';
	// import Journal_entry_obj_qry from './../ae_comp__journal_entry_obj_qry.svelte';
	import Journal_obj_id_edit from '../ae_comp__journal_obj_id_edit.svelte';

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

	// Variables
	// *** Quickly pull out data from parent(s)
	let ae_acct = data[$slct.account_id];
	$effect(() => {
		if (log_lvl > 1) {
			console.log(`ae_acct = `, ae_acct);
		}
	});

	$inspect(log_lvl, `log_lvl = ${log_lvl}`);
	$inspect($journals_slct.journal_id, `$journals_slct.journal_id = ${$journals_slct.journal_id}`);
	$inspect(
		$journals_slct.journal_entry_id,
		`$journals_slct.journal_entry_id = ${$journals_slct.journal_entry_id}`
	);

	// $inspect($journals_slct.journal_entry_id).with((type, val) => {
	//     if (type === 'update') {
	//         // debugger; // or `console.trace`, or whatever you want
	//         console.log('$journals_slct.journal_entry_id updated:', val);
	//     }
	// });

	// For some reason data.params.journal_id (or whatever param) is not being passed to this page when loaded by a link from another page. This seems to be a bug with Svelte or SvelteKit. Hopefully fixed in a future version 5? 2024-11-06
	// $journals_slct.journal_id = ae_acct.slct.journal_id;
	// $journals_slct.journal_obj = ae_acct.slct.journal_obj;

	$journals_slct.journal_id = ae_acct.slct.journal_id;

	$journals_sess.entry_li = [];
	$journals_slct.journal_entry_id = null;

	let lq__journal_obj = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal.get($journals_slct?.journal_id ?? ''); // null or undefined does not reset things like '' does

			// Check if results are different than the current session version stored under $journals_slct
			if ($journals_slct.journal_obj && results) {
				if (JSON.stringify($journals_slct.journal_obj) !== JSON.stringify(results)) {
					$journals_slct.journal_obj = { ...results };
				}
			}

			return results;
		})
	);

	$effect(() => {
		if (log_lvl) {
			console.log(`lq__journal_obj: journal_id = ${$journals_slct?.journal_id}`);
			console.log(`lq__journal_obj: results = `, lq__journal_obj);
			if ($journals_slct.journal_obj && lq__journal_obj) {
				if (JSON.stringify($journals_slct.journal_obj) !== JSON.stringify(lq__journal_obj)) {
					console.log(
						`Session slct stored version has changed for ID = ${$journals_slct.journal_id}`,
						$journals_slct.journal_obj
					);
				} else {
					console.log(
						`Session slct stored version has not changed for ID = ${$journals_slct.journal_id}`
					);
				}
			}
		}
	});

	let lq__journal_entry_obj_li = $derived(
		liveQuery(async () => {
			let results;

			if ($journals_sess.entry_li_trigger && !$journals_sess?.entry_li) {
				$journals_sess.entry_li = null;
				$journals_sess.entry_li_trigger = false;
			}

			if ($journals_sess?.entry_li && $journals_sess?.entry_li?.length) {
				let journal_entry_id_random_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

				for (let i = 0; i < $journals_sess?.entry_li.length; i++) {
					let journal_entry_obj = $journals_sess?.entry_li[i];
					let journal_entry_id_random = journal_entry_obj.journal_entry_id_random;
					journal_entry_id_random_li.push(journal_entry_id_random);
				}
				// let journal_entry_id_random_li = tmp_li;

				results = await db_journals.journal_entry.bulkGet(journal_entry_id_random_li);
			} else if ($lq__journal_obj?.cfg_json?.entry_group_sort === 'DESC') {
				results = await db_journals.journal_entry
					// .orderBy('updated_on')
					.where('journal_id')
					.equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
					.reverse()
					// .sortBy('tmp_sort_2');
					.sortBy('updated_on');
				// .sortBy('title');
			} else if (
				$journals_loc.filter__category_code &&
				$journals_loc.filter__category_code.length > 0
			) {
				results = await db_journals.journal_entry
					.where('journal_id')
					.equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
					.and((entry) => entry.category_code === $journals_loc.filter__category_code)
					.reverse()
					.sortBy('tmp_sort_1');
			} else {
				results = await db_journals.journal_entry
					.where('journal_id')
					.equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
					.reverse()
					.sortBy('tmp_sort_1');
				// .sortBy('updated_on');
			}

			// Check if results are different than the current session version stored under $journals_slct
			if (
				$journals_slct.journal_entry_obj_li &&
				JSON.stringify($journals_slct.journal_entry_obj_li) !== JSON.stringify(results)
			) {
				$journals_slct.journal_entry_obj_li = [...results];
			}

			return results;
		})
	);

	$effect(() => {
		if (log_lvl) {
			console.log(`LQ - $lq__journal_obj.cfg_json = `, $lq__journal_obj?.cfg_json);
			console.log(
				`LQ - $journals_loc.filter__category_code = `,
				$journals_loc.filter__category_code
			);
			if ($journals_sess?.entry_li && $journals_sess?.entry_li?.length) {
				console.log(`LQ - Using $journals_sess.entry_li to get journal entries.`);
			} else if ($lq__journal_obj?.cfg_json?.entry_group_sort === 'DESC') {
				console.log(
					`LQ - Using DESC sort for Journal Entry list journal_id: ${$journals_slct?.journal_id}`
				);
			} else if (
				$journals_loc.filter__category_code &&
				$journals_loc.filter__category_code.length > 0
			) {
				console.log(`LQ - Using category filter: ${$journals_loc.filter__category_code}`);
			} else {
				console.log(
					`LQ - Using default sort for Journal Entry list journal_id: ${$journals_slct?.journal_id}`
				);
			}
			if (
				$journals_slct.journal_entry_obj_li &&
				JSON.stringify($journals_slct.journal_entry_obj_li) !==
					JSON.stringify(lq__journal_entry_obj_li)
			) {
				console.log(
					`Session slct li stored version has changed for ID = ${$journals_slct.journal_id}`,
					$journals_slct.journal_entry_obj_li
				);
			} else {
				if (log_lvl > 1) {
					console.log(
						`Session slct li stored version has not changed for ID = ${$journals_slct.journal_id}`
					);
				}
			}
		}
	});

	// Trigger doing a basic load of journal entries
	// NOTE: Categories are (currently) filtered at the CSS style level.
	$effect(() => {
		if ($journals_trig.journal_entry_li) {
			$journals_trig.journal_entry_li = false;

			// if ($journals_trig?.journal_entry_li.length > 0) {
			//     $journals_sess.entry_li = $journals_trig.journal_entry_li;
			//     console.log('TEST TEST TEST');
			//     return ;
			// }

			if (log_lvl) {
				console.log(`Triggered: $journals_trig.journal_entry_li`);
			}

			if ($journals_loc.qry__enabled !== 'all' || $journals_loc.qry__hidden !== 'all') {
				if (log_lvl) {
					console.log(
						`Not set to all for enabled or hidden. Clearing all  journal entries to be safe.`
					);
					console.log(`$journals_loc.qry__enabled = ${$journals_loc.qry__enabled}`);
					console.log(`$journals_loc.qry__hidden = ${$journals_loc.qry__hidden}`);
				}
				let results = db_journals.journal_entry.clear();
				if (log_lvl) {
					console.log(`Cleared all journal entries in the database.`, results);
				}
			}

			$journals_prom.load__journal_entry_obj_li = journals_func.load_ae_obj_li__journal_entry({
				api_cfg: $ae_api,
				for_obj_type: 'journal',
				for_obj_id: $journals_slct.journal_id,
				enabled: $journals_loc.qry__enabled,
				hidden: $journals_loc.qry__hidden,
				limit: $journals_loc.qry__limit,
				order_by_li: $journals_loc.qry__order_by_li,
				try_cache: true,
				log_lvl: log_lvl
			});

			// Should we reset the entry list???
			// $journals_sess.entry_li = null;
		}
	});

	if (browser) {
		let message = { journal_id: $journals_slct?.journal_id ?? null };
		window.parent.postMessage(message, '*');
	}
</script>

<svelte:head>
	<title>
		Æ Journals:
		{$lq__journal_obj?.name
			? ae_util.shorten_string({
					string: $lq__journal_obj?.name,
					max_length: 20,
					begin_length: 10,
					end_length: 4
				})
			: ''}
		- {$ae_loc?.title}
	</title>
</svelte:head>

{#if $ae_loc.person_id == $lq__journal_obj?.person_id}
	<!-- Svelte Page for a Journal ID page -->
	<!-- <section
    class="
        ae_journals__journal
        container h-full mx-auto
        flex flex-col gap-1
        py-1 px-2 pb-16
        items-center
        min-w-full
        max-w-max
        "
    > -->

	<Journal_view {lq__journal_obj} {lq__journal_entry_obj_li} />

	{#if $lq__journal_entry_obj_li && $lq__journal_entry_obj_li?.length}
		<Journal_entry_obj_li {lq__journal_obj} {lq__journal_entry_obj_li} />
	{:else}
		<section class="main_content grow px-1 md:px-2 pb-28 flex flex-col gap-1 items-center">
			<p>No journal entry available to show.</p>
		</section>
	{/if}

	<!-- </section> -->

	<!-- Modal: Journal edit ID -->
	<!-- tmp__journal_obj={$journals_slct.journal_obj} -->
	<Journal_obj_id_edit
		{log_lvl}
		{lq__journal_obj}
		show={$journals_sess.show__modal_edit__journal_obj}
	/>
{:else}
	<section class="main_content grow px-1 md:px-2 pb-28 flex flex-col gap-1 items-center">
		<p class="text-center">You must be logged in as the owner to view this Journal.</p>
	</section>
{/if}
