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

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

// *** Import other supporting libraries
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 { db_archives } from "$lib/ae_archives/db_archives";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/ae_idaa_stores';
import { archives_func } from '$lib/ae_archives/ae_archives_functions';

import Archive_obj_id_edit from './ae_idaa_comp__archive_obj_id_edit.svelte';
import Archive_view from './ae_idaa_comp__archive_obj_id_view.svelte';
// import Archive_page_menu from './session_page_menu.svelte';
// import Element_data_store from '$lib/element_data_store_v2.svelte';

import Archive_content_obj_li from './ae_idaa_comp__archive_content_obj_li.svelte';
import Archive_content_obj_id_edit from './ae_idaa_comp__archive_content_obj_id_edit.svelte';
// import Media_player from './../ae_idaa_comp__media_player.svelte';
import Modal_media_player from './ae_idaa_comp__modal_media_player.svelte';

interface Props {
    data: any;
}

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

// 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];
if (log_lvl) {
    console.log(`ae_acct = `, ae_acct);
}

// For some reason data.params.archive_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
$idaa_slct.archive_id = ae_acct.slct.archive_id;
// $idaa_slct.archive_obj = ae_acct.slct.archive_obj;


let lq__archive_obj = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`lq__archive_obj: archive_id = ${$idaa_slct?.archive_id}`);
    }
    let results = await db_archives.archive
        .get($idaa_slct?.archive_id ?? ''); // null or undefined does not reset things like '' does

    return results;
}));

let lq__archive_content_obj_li = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`$lq__archive_obj.cfg_json = `, $lq__archive_obj?.cfg_json);
    }
    if ($lq__archive_obj?.cfg_json?.content_group_sort === 'DESC') {
        let results = await db_archives.content
            // .orderBy('updated_on')
            .where('archive_id')
            .equals($idaa_slct?.archive_id ?? '') // null or undefined does not reset things like '' does
            .reverse()
            .sortBy('tmp_sort_2');
            // .sortBy('updated_on');
            // .sortBy('title');

        return results;
    } else {
        let results = await db_archives.content
            .where('archive_id')
            .equals($idaa_slct?.archive_id ?? '') // null or undefined does not reset things like '' does
            // .reverse()
            .sortBy('tmp_sort_2');

        return results;
    }

}));

let lq__archive_content_obj = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`lq__archive_content_obj: archive_content_id = ${$idaa_slct?.archive_content_id}`);
    }
    if ($idaa_slct.archive_content_id) {
        let results = await db_archives.content
            .get($idaa_slct.archive_content_id); // null or undefined does not reset things like '' does

        return results;
    }
    // const results = await db_archives.content
    //     .get($idaa_slct.archive_content_id); // null or undefined does not reset things like '' does

    // return results;
}));


$effect(() => {
        if ($idaa_trig.archive_content_li) {
        $idaa_trig.archive_content_li = false;

        if (log_lvl) {
            console.log(`Triggered: $idaa_trig.archive_content_li`);
        }

        if ($idaa_loc.archives.qry__enabled !== 'all' || $idaa_loc.archives.qry__hidden !== 'all') {
            console.log(`Deleting disabled or hidden archive content.`);
            // let results = db_archives.content
            //     .where('enable')
            //     .notEqual(true)
            //     .delete();
            let results = db_archives.content
                .clear();
            console.log(`Deleted ${results} disabled archive content.`);

        }
        // if ($idaa_loc.archives.qry__hidden !== 'all') {
        //     console.log(`Deleting hidden archive content.`);
        //     let results = db_archives.content
        //         .clear();
        //     console.log(`Deleted ${results} hidden archive content.`);

        // }
        // let results = db_archives.content
        //     .where('enable')
        //     .equals('false')
        //     .delete();
        // console.log(`Deleted ${results} disabled archive content.`);

        $idaa_prom.load__archive_content_obj_li = archives_func.load_ae_obj_li__archive_content({
            api_cfg: $ae_api,
            for_obj_type: 'archive',
            for_obj_id: $idaa_slct.archive_id,
            enabled: $idaa_loc.archives.qry__enabled,
            hidden: $idaa_loc.archives.qry__hidden,
            limit: $idaa_loc.archives.qry__limit,
            order_by_li: $idaa_loc.archives.qry__order_by_li,
            try_cache: true,
            log_lvl: log_lvl,
        });
    }
    });

if (browser) {
    console.log('Browser environment detected.');

    let message = {'archive_id': $idaa_slct?.archive_id ?? null};
    window.parent.postMessage(message, "*");
}

</script>


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


<section
    class="
        ae_idaa__bb
        container h-full mx-auto
        flex flex-col gap-1
        py-1 px-2 pb-16
        items-center
        min-w-full
        max-w-max
        "
    >

<!-- <h1>Archives {$lq__archive_obj?.name} - {$lq__archive_content_obj_li?.length}</h1> -->

<a href="/idaa/archives" class="novi_btn btn btn-secondary btn-sm
    preset-tonal-tertiary border border-tertiary-500
    hover:preset-filled-tertiary-500
    transition
    ">
    <!-- <span class="fas fa-arrow-left m-1"></span> Back to Archives -->
     <span class="fas fa-times m-1"></span> View Other Archives
</a>

<Archive_view
    lq__archive_obj={lq__archive_obj}
    lq__archive_content_obj_li={lq__archive_content_obj_li}
    />

<!-- {#if $lq__archive_content_obj_li && $lq__archive_content_obj_li?.length } -->
    <Archive_content_obj_li
        lq__archive_content_obj_li={lq__archive_content_obj_li}
        />
<!-- {:else} -->
    <!-- <p>No archive content available to show.</p> -->
<!-- {/if} -->


</section>


<!-- Modal: Archive edit ID -->
<Modal
    title="{$lq__archive_obj?.name} - {$lq__archive_obj?.id}"
    bind:open={$idaa_sess.archives.show__modal_edit__archive_id}
    autoclose={false}
    placement="top-center"
    size="xl"
    class="top-center bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
    >

    {#snippet header()}

            <div class="flex flex-row items-center justify-between w-full">
                <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access}
                <!-- <div class="ae_options"> -->
                    <button
                        onclick={() => {
                        // const url = new URL(location);
                        // url.searchParams.set('event_id', $lq__archive_obj?.event_id_random);
                        // history.pushState({}, '', url);

                        $idaa_sess.archives.show__modal_view__archive_id = $idaa_slct.archive_id;
                        $idaa_sess.archives.show__modal_edit__archive_id = false;
                    }}
                        class="novi_btn btn btn-sm preset-tonal-warning border border-warning-500 hover:preset-filled-warning-500 transition"
                        title={`View meeting: ${$lq__archive_obj?.name}`}
                        >
                        <span class="fas fa-eye m-1"></span> View
                    </button>
                <!-- </div> -->
                {/if}

                <span class="text-sm text-gray-500">
                    Edit Archive:
                </span>
                {$lq__archive_obj?.name}
            </h3>
            </div>


    {/snippet}

    <Archive_obj_id_edit
        lq__archive_obj={lq__archive_obj}
        />

</Modal>


<!-- Modal: Archive Content edit ID -->
<Modal
    bind:open={$idaa_sess.archives.show__modal_edit__archive_content_id}
    title="{$lq__archive_content_obj?.name ?? 'New Archive Content'} - {$lq__archive_content_obj?.id ?? 'Not Saved Yet'}"
    autoclose={false}
    placement="top-center"
    size="xl"
    class="top-center bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
    >

    {#snippet header()}

            <div class="flex flex-row items-center justify-between w-full">
                <h3 class="text-lg font-semibold">
                    {#if $ae_loc.trusted_access}
                    <!-- <div class="ae_options"> -->
                        <button
                            onclick={() => {
                            // const url = new URL(location);
                            // url.searchParams.set('event_id', $lq__archive_content_obj?.event_id_random);
                            // history.pushState({}, '', url);

                            $idaa_sess.archives.show__modal_view__archive_content_id = $idaa_slct.archive_content_id;
                            $idaa_sess.archives.show__modal_edit__archive_content_id = false;
                        }}
                            class="novi_btn btn btn-sm preset-tonal-warning border border-warning-500 hover:preset-filled-warning-500 transition"
                            title={`View meeting: ${$lq__archive_content_obj?.name}`}
                            >
                            <span class="fas fa-eye m-1"></span> View
                        </button>
                    <!-- </div> -->
                    {/if}

                    <span class="text-sm text-gray-500">
                        Edit Archive Content:
                    </span>
                    {$lq__archive_content_obj?.name ?? 'New Archive Content'}
                </h3>
            </div>


    {/snippet}

    <Archive_content_obj_id_edit
        lq__archive_content_obj={lq__archive_content_obj}
        />

</Modal>


<!-- Modal: Archive Content ID media player -->
{#if $idaa_slct.archive_content_id && $idaa_sess.archives.show__modal_view__archive_content_id}
    <Modal_media_player
        lq__archive_content_obj={lq__archive_content_obj}
        />
{/if}
