<script lang="ts">

interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
}
let { data }: Props = $props();

let log_lvl: number = $state(0);

// *** Import Svelte specific
import { page } from '$app/state';
import { browser } from '$app/environment';
// import { goto, invalidate, pushState, replaceState } from '$app/navigation';

// *** 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_posts } from "$lib/ae_posts/db_posts";
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 { posts_func } from '$lib/ae_posts/ae_posts_functions';

import Comp__post_obj_li from './ae_idaa_comp__post_obj_li.svelte';
// import Comp__post_obj_id_view from './ae_idaa_comp__post_obj_id_view.svelte';
import Comp__post_options from './ae_idaa_comp__post_options.svelte';


let post_id = page.url.searchParams.get('post_id') ?? null;
if (!post_id) {
    $idaa_slct.post_id = null;
} else {
    console.log(`ae Posts - [post_id] +page.ts: post_id = `, post_id);
    $idaa_slct.post_id = post_id;
    $idaa_trig.post_id = post_id;
}

// Functions and Logic
let lq__post_obj_li = $derived(liveQuery(async () => {
    let results = await db_posts.post
        .where('account_id')
        .equals($slct.account_id)
        // .orderBy('updated_on')
        // .toArray()
        .reverse()
        .sortBy('tmp_sort_1');
        // .sortBy('updated_on');
        // .sortBy('updated_on, created_on');
        // .sortBy('[updated_on+created_on]');
        // .sortBy('[created_on+updated_on]');

    return results;
}));

let lq__post_obj = $derived(liveQuery(async () => {
    let results = await db_posts.post
        .get($idaa_slct.post_id ?? ''); // null or undefined does not reset things like '' does

    return results;
}));

let lq__post_comment_obj_li = $derived(liveQuery(async () => {
    let results = await db_posts.comment
        .where('post_id')
        .equals($idaa_slct.post_id ?? '') // null or undefined does not reset things like '' does
        .reverse()
        .sortBy('updated_on');
        // .sortBy('title');

    return results;
}));

let lq__post_comment_obj = $derived(liveQuery(async () => {
    let results = await db_posts.comment
        .get($idaa_slct.post_comment_id ?? ''); // null or undefined does not reset things like '' does

    return results;
}));


$effect(() => {
    if ($idaa_trig.post_li) {
        $idaa_trig.post_li = false;
        log_lvl = 1;

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

        // This may need to be rethought... For now things are cleared  if query is anything but 'all' for enabled and hidden.
        if ($idaa_loc.bb.qry__enabled !== 'all' || $idaa_loc.bb.qry__hidden !== 'all' || $idaa_loc.bb.qry__limit < 50) {
            console.log(`Deleting disabled or hidden post.`);
            let results = db_posts.post
                .clear();
            console.log(`Deleted ${results} disabled post.`);

            console.log(`Deleting disabled or hidden post comments.`);
            results = db_posts.comment
                .clear();
            console.log(`Deleted ${results} disabled post comments.`);
        }

        $idaa_prom.load__post_obj_li = posts_func.load_ae_obj_li__post({
            api_cfg: $ae_api,
            for_obj_type: 'account',
            for_obj_id: $idaa_slct.account_id,
            inc_comment_li: true,
            enabled: $idaa_loc.bb.qry__enabled,
            hidden: $idaa_loc.bb.qry__hidden,
            limit: $idaa_loc.bb.qry__limit,
            order_by_li: $idaa_loc.bb.qry__order_by_li,
            // try_cache: true,
            log_lvl: log_lvl,
        });
    }
});

// $effect(() => {
//     if ($idaa_trig.post_id) {
//         // log_lvl = 1;
//         $idaa_trig.post_id = false;

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

//         $idaa_prom.load__post_obj = posts_func.load_ae_obj_id__post({
//             api_cfg: $ae_api,
//             post_id: $idaa_slct.post_id,
//             enabled: $idaa_loc.bb.qry__enabled,
//             hidden: $idaa_loc.bb.qry__hidden,
//             limit: $idaa_loc.bb.qry__limit,
//             inc_comment_li: true,
//             // try_cache: true,
//             log_lvl: log_lvl,
//         })
//         .then((post_obj) => {
//             if (log_lvl) {
//                 console.log(`Post object loaded: `, post_obj);
//             }

//             $idaa_slct.post_obj = post_obj;
//             $idaa_slct.post_comment_id = null;
//             $idaa_slct.post_comment_obj = null;

//             // $idaa_sess.bb.show__modal_view__post_id = $idaa_slct.post_id;
//             // $idaa_sess.bb.show__modal_edit__post_id = false;
//         });

//         // $idaa_slct.post_obj = $idaa_prom.load__post_obj;

//         if (!page.url.searchParams.get('post_id')) {
//             const url = new URL(location);
//             // url.searchParams.set('post_id', $idaa_slct.post_id);
//             url.searchParams.delete('post_id');
//             history.pushState({}, '', url);

//             let message = {'post_id': $idaa_slct.post_id};
//             window.parent.postMessage(message, "*");
//         }

//         $idaa_sess.bb.show__modal_view__post_id = $idaa_slct.post_id;
//         $idaa_sess.bb.show__modal_edit__post_id = false;
//     }
// });


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

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

    add_activity_log(
        {
            action: 'idaa_bb_page',
            action_with: 'browser',
        }
    );
}


function add_activity_log(
        {
            action = 'idaa_bb_page',
            action_with = 'none',
        }: {
            action?: string,
            action_with?: string,
        }
    ) {

    let last_cache_refresh_iso = new Date($ae_loc?.last_cache_refresh);

    let activity_description = `
        ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? 'no-email'}
        allow=${$ae_loc?.allow_access}
        last_cache_refresh=${last_cache_refresh_iso.toLocaleString()}
        data_route=${data?.route.toString() ?? 'unknown'}
    `;

    let data_kv = {
        external_client_id: data?.route.id,
        name: `IDAA: ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? ''}`,
        description: activity_description ?? null,
        object_type: 'post', // archive, post, event
        // object_id_random: data?.params?.event_id ?? null,
        // object_id_random: ae_acct.slct.archive_id, // data?.params?.archive_id ?? null,
        url_root: data?.url.origin,
        // url_full_path: data?.url.href,
        url_full_path: data?.url.pathname,
        url_params: data?.url.searchParams.toString(),
        action: action,
        action_with: action_with ?? 'none',
        meta_json: {
            allow_access: $ae_loc?.allow_access,
            last_cache_refresh: $ae_loc?.last_cache_refresh,
            last_cache_refresh_iso: last_cache_refresh_iso.toISOString(),
            last_cache_refresh_locale: last_cache_refresh_iso.toLocaleString(),
            access_level: $ae_loc?.access_level,
            iframe: $ae_loc?.iframe,
            // site_access_key: $ae_loc?.site_access_key,
            // site_domain_access_key: $ae_loc?.site_domain_access_key,
            // site_domain: $ae_loc?.site_domain,
            // extra_data: extra_data ?? '',
            // log_lvl: log_lvl,
        }
    };

    core_func.create_ae_obj__activity_log({
        api_cfg: $ae_api,
        account_id: $ae_loc.account_id,
        data_kv: data_kv,
        log_lvl: log_lvl
    });
}
</script>


<svelte:head>
	<title>
        IDAA Bulletin Board:
        - 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
        "
    > -->


<Comp__post_options
    />

<!-- <h1>Bulletin Board {$lq__post_obj_li?.length}</h1> -->

{#if $lq__post_obj_li && $lq__post_obj_li?.length}
    <Comp__post_obj_li
        lq__post_obj_li={lq__post_obj_li}
        />
{:else}
    <p>No posts available to show.</p>
{/if}


<!-- </section> -->
