<script lang="ts">
/** @type {import('./$types').PageData} */
export let data: any;
let log_lvl: number = 0;
// console.log(`ae_events_pres_mgmt event [event_id] +page.svelte data:`, data);

import { browser } from '$app/environment';
// import { goto, invalidate, pushState, replaceState } from '$app/navigation';

import { Modal } from 'flowbite-svelte';

// import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/ae_idaa_stores';
// import Element_data_store from '$lib/element_data_store_v2.svelte';
// import Comp_event_session_obj_li from '../../events_pres_mgmt/ae_comp__event_session_obj_li.svelte';

import { liveQuery } from "dexie";
// import { core_func } from '$lib/ae_core/ae_core_functions';
import { db_events } from "$lib/ae_events/db_events";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { events_func } from '$lib/ae_events_functions';

import Element_data_store from '$lib/element_data_store_v2.svelte';

import Comp__event_obj_qry from './ae_idaa_comp__event_obj_qry.svelte';
import Comp__event_obj_li from './ae_idaa_comp__event_obj_li.svelte';
import Comp__event_obj_id_edit from './ae_idaa_comp__event_obj_id_edit.svelte';
import Comp__event_obj_id_view from './ae_idaa_comp__event_obj_id_view.svelte';

let event_id_random_li: Array<string>;


// Functions and Logic
$: lq__event_obj = liveQuery(async () => {
    let results = await db_events.events
        .get($idaa_slct.event_id);

    return results;
});


$: lq_new__event_obj_li = liveQuery(async () => {
    let link_to_type: string = 'account';
    let link_to_id: string = $slct.account_id;
    if (log_lvl > 1) {
        console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}; event_id_random_li:`, event_id_random_li);
    }

    // Check if event_id_random_li is an array and not undefined
    if (event_id_random_li) {
        if (log_lvl) {
            console.log(`Trying bulkGet:`, event_id_random_li);
        }
        let results = await db_events.events
            .bulkGet(event_id_random_li);

        return results;
    } else if (link_to_type && link_to_id) {
        if (log_lvl) {
            console.log(`Trying where: ${link_to_type}; equals: ${link_to_id}`);
        }
        let results: any = null;
        if ($idaa_loc.recovery_meetings.qry__order_by == 'name') {
            results = await db_events.events
                .where(`${link_to_type}_id`)
                .equals(link_to_id)
                .and((event) => {
                    return event.hide == false;
                })
                .and((event) => {
                    return event.enable == true;
                })
                .sortBy('name')
        } else {
            results = await db_events.events
                .where(`${link_to_type}_id`)
                .equals(link_to_id)
                .and((event) => {
                    return event.hide == false;
                })
                .and((event) => {
                    return event.enable == true;
                })
                .sortBy('updated_on')
        }

        return results;
    } else {
        if (log_lvl) {
            console.log('Trying... Nothing to load');
        }
        return null;
    }
});


// This (event_li trigger for IDAA) is not currently being used.
// Updated 2024-11-19
$: if ($idaa_trig.event_li) {
    $idaa_trig.event_li = false;

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

    if ($idaa_loc.recovery_meetings.qry__enabled !== 'all' || $idaa_loc.recovery_meetings.qry__hidden !== 'all') {
        console.log(`Deleting disabled or hidden event.`);
        let results = db_events.events
            .clear();
        console.log(`Deleted ${results} disabled event.`);

    }

    $idaa_prom.load__event_obj_li = events_func.load_ae_obj_li__event({
        api_cfg: $ae_api,
        for_obj_type: 'account',
        for_obj_id: $idaa_slct.account_id,
        qry_conference: false,
        enabled: $idaa_loc.recovery_meetings.qry__enabled,
        hidden: $idaa_loc.recovery_meetings.qry__hidden,
        limit: $idaa_loc.recovery_meetings.qry__limit,
        order_by_li: $idaa_loc.recovery_meetings.qry__order_by_li,
        try_cache: true,
        log_lvl: log_lvl,
    });
}


// Updated 2024-11-19
$: if ($idaa_trig.event_li_qry) {
    $idaa_trig.event_li_qry = false;

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

    // $idaa_sess.recovery_meetings.qry__status = 'loading';

    let and_physical = $idaa_loc.recovery_meetings.qry__physical;
    let and_virtual = $idaa_loc.recovery_meetings.qry__virtual;
    let and_type = $idaa_loc.recovery_meetings.qry__type;
    let order_by_li = $idaa_loc.recovery_meetings.qry__order_by_li;
    let search_delay = 15;
    let max_tries = 5;
    let try_cache = true;

    // let params = {
    //         'qry__enabled': $idaa_loc.recovery_meetings.qry__enabled ?? 'enabled',
    //         'qry__hidden': $idaa_loc.recovery_meetings.qry__hidden ?? 'not_hidden',
    //         'qry__limit': $idaa_loc.recovery_meetings.qry__limit ?? 35,
    //     };


    if ($idaa_loc.recovery_meetings.qry__enabled !== 'all' || $idaa_loc.recovery_meetings.qry__hidden !== 'all') {
        console.log(`Deleting disabled or hidden event.`);
        let results = db_events.events
            .clear();
        console.log(`Deleted ${results} disabled event.`);

    }

    if ($idaa_sess.recovery_meetings?.qry__status != null && $idaa_sess.recovery_meetings?.qry__status != 'done') {
        console.log('*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status != done ***');
        // WARNING: This is a temporary fix for the search string. It needs to be fixed in the future. Using lk_search_str for now.
        $idaa_sess.recovery_meetings.status_qry__last_request_str = $idaa_loc.recovery_meetings.qry__fulltext_str;

        // We want to delay the initial search request to give the previous search request to finish.
        let random_delay = Math.floor(Math.random() * 50);
        search_delay += 50+random_delay;
    }

    log_lvl = 1;

    let count = 0;
    let request_loop = setInterval(() => {
        count++;
        if (log_lvl) {
            console.log(`*** TEST SEARCH - Search delay: ${search_delay} *** loop count=${count}`);
        }
        if (count >= max_tries) {
            console.log('*** TEST SEARCH - Max tries reached ***');
            clearInterval(request_loop);
        }

        if ($idaa_sess.recovery_meetings?.qry__status != null && $idaa_sess.recovery_meetings?.qry__status != 'done') {
            let random_delay = Math.floor(Math.random() * 25);
            search_delay += 25+random_delay;
            console.log(`*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status == loading wait *** search_delay=${search_delay}`);
            // $idaa_sess.status_qry__last_request_str = $idaa_loc.recovery_meetings.qry__fulltext_str;
        } else {
            console.log('*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status != loading ***');

            $idaa_sess.recovery_meetings.qry__status = 'loading';

            (and_physical) ?? null;
            (and_virtual) ?? null;
            (and_type) ?? null;
            // if (and_type) and_type = and_type;
            // if (!and_type) {
            //     and_type = null;
            // }

            console.log(`TEST - and_physical: ${and_physical}; and_virtual: ${and_virtual}; and_type: ${and_type}; qry__fulltext_str: ${$idaa_loc.recovery_meetings.qry__fulltext_str}`);

            $idaa_prom.load__event_obj_qry = events_func.qry_ae_obj_li__event({
                api_cfg: $ae_api,
                for_obj_type: 'account',
                for_obj_id: $ae_loc.account_id,
                order_by_li: order_by_li,
                qry_conference: false,
                qry_physical: and_physical,
                qry_virtual: and_virtual,
                qry_type: and_type,
                qry_str: $idaa_loc.recovery_meetings.qry__fulltext_str,
                try_cache: try_cache,
                log_lvl: log_lvl,
            })
            .then(function (search_results) {
                // Processing the results from the search.
                $idaa_sess.recovery_meetings.qry__status = 'processing';
                $idaa_slct.event_obj_li = search_results;
                console.log(search_results);
                // $idaa_sess.recovery_meetings.qry__status = 'done';

                if (log_lvl) {
                    console.log('TEST SEARCH - Search done. Pulling out the event_id_randoms.');
                }
                // console.log(`TEST search: ${$lq_kv__event_obj_li}`);

                // event_id_random_li = [];

                // We need to loop through the array of objects and get the event_id_random from each object a new list of event_id_randoms. Then we can use this list to get the full objects from the database.
                let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
                if (search_results && search_results.length) {
                    for (let i = 0; i < search_results.length; i++) {
                        tmp_li.push($idaa_slct.event_obj_li[i].event_id_random);
                    }
                }
                event_id_random_li = tmp_li;
            })
            .finally(() => {


                // event_id_random_li = $idaa_slct.event_obj_li.map(session_obj => session_obj.event_id_random);

                // Finally done with the search.
                $idaa_sess.recovery_meetings.qry__status = 'done';

                if (log_lvl > 1) {
                    console.log(`TEST SEARCH - event_id_random_li:`, event_id_random_li);
                    // console.log(`TEST SEARCH - search live query: ${$lq_kv__event_obj_li}`);
                }

            });
            clearInterval(request_loop);
        }
    }, search_delay);

}


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

    if (!$idaa_sess.recovery_meetings.show__modal_edit && !$idaa_sess.recovery_meetings.show__modal_view) {
        $idaa_slct.event_id = null;
    }

    let message = {'event_id': $idaa_slct?.event_id ?? null};
    window.parent.postMessage(message, "*");
}
</script>


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


<section
    class="
        ae_idaa__recovery_meetings
        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__event_obj_qry
    bind:event_id_random_li={event_id_random_li}
    />


<Element_data_store
    ds_code="recovery_meetings_info"
    ds_type="html"
    class_li="border border-1 rounded-lg bg-gray-100 p-2 max-w-screen-lg space-y-2"
    />


{#if $lq_new__event_obj_li && $lq_new__event_obj_li?.length }
    <Comp__event_obj_li
        lq__event_obj_li={lq_new__event_obj_li}
        />
{:else}
    <p>No recovery meetings available to show.</p>
{/if}


</section>


<!-- Modal: Event (Recovery Meeting) edit ID -->
<Modal
    title="{$lq__event_obj?.name} - {$lq__event_obj?.id}"
    bind:open={$idaa_sess.recovery_meetings.show__modal_edit}
    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"
    >

    <svelte:fragment slot="header">
        <div class="flex flex-row items-center justify-between w-full">
            <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access || $lq__event_obj?.external_person_id === $idaa_loc.novi_uuid || $lq__event_obj?.contact_li_json[0]?.email === $idaa_loc.novi_email}
                <!-- <div class="ae_options"> -->
                    <button
                        on:click={() => {
                            // const url = new URL(location);
                            // url.searchParams.set('event_id', $lq__event_obj?.event_id_random);
                            // history.pushState({}, '', url);

                            $idaa_sess.recovery_meetings.show__modal_edit = false;
                            $idaa_sess.recovery_meetings.show__modal_view = true;
                        }}
                        class="novi_btn btn btn-sm variant-ghost-warning hover:variant-filled-warning transition"
                        title={`View meeting: ${$lq__event_obj?.name}`}
                        >
                        <span class="fas fa-times m-1"></span> Cancel Edit
                    </button>
                <!-- </div> -->
                {/if}

                <span class="fas fa-calendar-day m-1"></span>
                {$lq__event_obj?.name ?? 'New Recovery Meeting'}
            </h3>
        </div>

    </svelte:fragment>

    <Comp__event_obj_id_edit
        lq__event_obj={lq__event_obj}
        />


    <svelte:fragment slot="footer">
        <div class="text-center w-full">
            <button
                type="button"
                on:click={() => {
                    console.log('Close modal');
                    $idaa_sess.recovery_meetings.show__modal_edit = false;
                }}
                class="novi_btn btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>
        </div>
    </svelte:fragment>

</Modal>


<!-- Modal: Event (Recovery Meeting) view ID -->
<Modal
    title="{$lq__event_obj?.name} - {$lq__event_obj?.id}"
    bind:open={$idaa_sess.recovery_meetings.show__modal_view}
    autoclose={false}
    outsideclose={true}
    placement="top-center"
    size="lg"
    class="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"
    >

    <svelte:fragment slot="header">

        <div class="flex flex-row items-center justify-between w-full">
            <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access || $lq__event_obj?.external_person_id === $idaa_loc.novi_uuid || $lq__event_obj?.contact_li_json[0].email === $idaa_loc.novi_email}
                    <button
                        on:click={() => {
                            // const url = new URL(location);
                            // url.searchParams.set('event_id', $lq__event_obj?.event_id_random);
                            // history.pushState({}, '', url);

                            $idaa_sess.recovery_meetings.show__modal_view = false;
                            $idaa_sess.recovery_meetings.show__modal_edit = true;
                        }}
                        class="novi_btn btn btn-sm variant-ghost-warning hover:variant-filled-warning transition"
                        title={`Edit meeting: ${$lq__event_obj?.name}`}
                        >
                        <span class="fas fa-edit m-1"></span> Edit
                    </button>
                {/if}
                <span class="fas fa-calendar-day m-1"></span>
                {$lq__event_obj?.name ?? '-- not set'}
            </h3>
        </div>
    </svelte:fragment>

    <Comp__event_obj_id_view
        lq__event_obj={lq__event_obj}
        />

</Modal>
