<script lang="ts">
interface Props {
    log_lvl?: number;
    lq__event_obj: any;

    event_session_obj_li?: any[];

    rpt__name?: string;
    rpt__sort?: string;
    rpt__order_by_li?: any;
    rpt__enabled?: string;
    rpt__hidden?: string;
    rpt__limit?: number;

    qry__status?: string;
    qry__count?: number;

    qry__trigger?: boolean;

    // show_presentation_fields?: boolean;
    // show_session_fields?: boolean;
    hide_session_code?: boolean;
}

let {
    log_lvl = $bindable(0),
    lq__event_obj, // This is the live query so it updates automatically anyways?

    event_session_obj_li = $bindable([]),

    rpt__name = $bindable('session_no_files'), // presenters_agree, presenters_biography, presenters_overview
    rpt__sort = $bindable('updated_on'), // updated_on, given_name, family_name, email, start_datetime
    rpt__order_by_li = $bindable({
        updated_on: 'DESC',
        priority: 'DESC',
        sort: 'DESC',
        given_name: 'ASC',
        family_name: 'ASC',
        email: 'ASC',
        created_on: 'DESC'
    }),
    rpt__enabled = $bindable('all'), // enabled, disabled, all
    rpt__hidden = $bindable('all'), // hidden, not_hidden, all
    rpt__limit = $bindable(150),

    qry__status = $bindable(''), // loading, processing, done
    qry__count = $bindable(0),

    qry__trigger = $bindable(true),

    // show_presentation_fields = false,
    // show_session_fields = false,
    hide_session_code = false
}: Props = $props();

// *** Import Svelte specific

// *** Import other supporting libraries

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
// import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
// import { db_events } from "$lib/ae_events/db_events";
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { pres_mgmt_loc } from '$lib/stores/ae_events_stores__pres_mgmt.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import Comp_event_session_obj_tbl from '../../../ae_comp__event_session_obj_tbl_wrapper.svelte';
import {
    Check,
    IdCard,
    LoaderCircle,
    ToggleLeft,
    ToggleRight,
    X
} from '@lucide/svelte';
let ae_promises: key_val = $state({});

let sort_option_kv: key_val = {
    updated_on: {
        name: 'Updated On',
        field_kv: {
            event_presentation_start_datetime: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            given_name: 'ASC',
            family_name: 'ASC',
            email: 'ASC',
            updated_on: 'DESC',
            created_on: 'DESC'
        }
    },
    given_name: {
        name: 'Given Name',
        field_kv: {
            given_name: 'ASC',
            family_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            email: 'ASC',
            created_on: 'DESC'
        }
    },
    family_name: {
        name: 'Family Name',
        field_kv: {
            family_name: 'ASC',
            given_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            email: 'ASC',
            created_on: 'DESC'
        }
    },
    email: {
        name: 'Email',
        field_kv: {
            email: 'ASC',
            given_name: 'ASC',
            family_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC'
        }
    },
    start_datetime: {
        name: 'Start Date Time',
        field_kv: {
            event_presentation_start_datetime: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            given_name: 'ASC',
            family_name: 'ASC',
            email: 'ASC',
            updated_on: 'DESC',
            created_on: 'DESC'
        }
    }
};

$effect(() => {
    if (qry__trigger) {
        qry__trigger = false;
        if (rpt__name == 'session_no_files') {
            handle_qry__event_session({
                qry_files: pres_mgmt_loc.current.rpt__session_no_files ?? false,
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else if (rpt__name == 'sessions_poc_agree') {
            handle_qry__event_session({
                // qry_poc_kv_json: false,
                qry_poc_agree:
                    pres_mgmt_loc.current.rpt__session_poc_agree ?? false,
                // order_by_li: rpt__order_by_li,
                log_lvl: 1
            });
        } else if (rpt__name == 'session_no_bio') {
            handle_qry__event_session({
                qry_poc_kv_json: true,
                qry_poc_bios:
                    pres_mgmt_loc.current.rpt__session_no_bio ?? false,
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        }
    }
});

// Updated 2024-10-15
async function handle_qry__event_session({
    qry_files = null,
    // file_count = false,
    // file_count_all = null,
    // ft_search_str = '',
    // lk_search_str = '',
    qry_poc_agree = null,
    qry_poc_kv_json = null,
    qry_poc_bios = null,
    enabled = pres_mgmt_loc.current.qry_enabled ?? 'enabled',
    hidden = pres_mgmt_loc.current.qry_hidden ?? 'not_hidden',
    limit = pres_mgmt_loc.current.qry_limit__sessions ?? 150,
    order_by_li = rpt__order_by_li,
    log_lvl = 0
}: {
    qry_files?: null | boolean;
    // file_count?: boolean,
    // file_count_all?: null|number,
    // ft_search_str?: string,
    // lk_search_str?: string,
    qry_poc_agree?: null | boolean;
    qry_poc_kv_json?: null | boolean;
    qry_poc_bios?: null | boolean;
    enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
    hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
    limit?: number;
    order_by_li?: key_val;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log('handle_qry__event_session()');
    }

    $events_sess.pres_mgmt.status_qry__search = 'loading';
    $events_sess.pres_mgmt.status_rpt[rpt__name] = 'loading';
    qry__status = 'loading';
    qry__count = 0;

    $events_sess.event_session_obj_li = [];
    $events_slct.event_session_obj_li = []; // Clear out any previous results.
    event_session_obj_li = [];

    ae_promises.handle_qry__event_session = events_func
        .qry__event_session({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            // file_count_all: file_count_all,
            // fulltext_search_qry_str: ft_search_str,
            // like_search_qry_str: lk_search_str,
            // external_event_id: pres_mgmt_loc.current.default__external_registration_id,
            qry_files: qry_files,
            qry_start_datetime: null,
            qry_poc_agree: qry_poc_agree,
            qry_poc_kv_json: qry_poc_kv_json,
            enabled: enabled,
            hidden: hidden,
            limit: limit,
            // order_by_li: order_by_li,
            log_lvl: log_lvl
        })
        .then(function (search_results) {
            // Processing the results from the search.
            $events_sess.pres_mgmt.status_qry__search = 'processing';
            $events_sess.pres_mgmt.status_rpt[rpt__name] = 'processing';
            qry__status = 'processing';
            qry__count = search_results?.length ?? 0;

            $events_sess.event_session_obj_li = search_results;
            event_session_obj_li = search_results;
            if (log_lvl) {
                console.log(`Search results:`, search_results);
            }
            // $events_sess.pres_mgmt.status_qry__search = 'done';
        })
        .finally(() => {
            if (log_lvl) {
                console.log(
                    'API query done. Pulling out the event_session_id_random values.'
                );
            }
            // console.log(`TEST search: ${$lq_kv__event_session_obj_li}`);

            // event_session_id_random_li = [];

            // We need to loop through the array of objects and get the event_session_id_random from each object a new list of event_session_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 ($events_slct.event_session_obj_li) {
                for (
                    let i = 0;
                    i < $events_slct.event_session_obj_li.length;
                    i++
                ) {
                    if (
                        qry_poc_bios &&
                        $events_slct.event_session_obj_li[i].poc_kv_json
                    ) {
                        if (
                            $events_slct.event_session_obj_li[i].poc_kv_json[
                                'champion'
                            ]?.biography.length > 1
                        ) {
                            console.log(
                                `Biography for session:`,
                                $events_slct.event_session_obj_li[i]
                            );
                            tmp_li.push(
                                $events_slct.event_session_obj_li[i]
                                    .event_session_id_random
                            );
                        } else {
                            console.log(
                                `No biography for session:`,
                                $events_slct.event_session_obj_li[i]
                            );
                        }
                    } else {
                        // console.log(`Pushing session to array (no biography):`, $events_slct.event_session_obj_li[i]);
                        tmp_li.push(
                            $events_slct.event_session_obj_li[i]
                                .event_session_id_random
                        );
                    }
                }
            }
            // event_session_id_random_li = tmp_li;

            // event_session_id_random_li = $events_slct.event_session_obj_li.map(session_obj => session_obj.event_session_id_random);

            // Finally done with the search.
            $events_sess.pres_mgmt.status_qry__search = 'done';
            $events_sess.pres_mgmt.status_rpt[rpt__name] = 'done';

            qry__status = 'done';

            // if (log_lvl > 1) {
            //     console.log(`TEST SEARCH - event_session_id_random_li:`, event_session_id_random_li);
            //     // console.log(`TEST SEARCH - search live query: ${$lq_kv__event_session_obj_li}`);
            // }
        });
}
</script>

<!-- Show sessions that have files -->
{#if rpt__name == 'session_no_files'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else if pres_mgmt_loc.current.rpt__session_no_files}
                <Check size="1em" class="m-1" />
            {:else}
                <X size="1em" class="m-1" />
            {/if}
            Sessions
            {#if pres_mgmt_loc.current.rpt__session_no_files}
                With
            {:else}
                Without
            {/if}
            Files
        </h3>

        <div class="flex flex-row items-center justify-center">
            <button
                type="button"
                onclick={() => {
                    pres_mgmt_loc.current.rpt__session_no_files =
                        !pres_mgmt_loc.current.rpt__session_no_files;

                    qry__trigger = true;
                    rpt__name = 'session_no_files';
                }}
                class="ae_btn_info btn-sm m-1">
                {#if pres_mgmt_loc.current.rpt__session_no_files}
                    <ToggleRight size="1em" class="m-1" />
                    With
                {:else}
                    <ToggleLeft size="1em" class="m-1" />
                    Without
                {/if}
            </button>
        </div>
    </header>
{/if}

<!-- Show sessions that have POC biographies -->
{#if rpt__name == 'sessions_no_bio'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else}
                <IdCard size="1em" class="m-1" />
                <!-- <span class="fas fa-book m-1"></span> -->
            {/if}
            Sessions
            {#if pres_mgmt_loc.current.rpt__session_no_bio}
                With
            {:else}
                Without
            {/if}
            POC Biography
        </h3>

        <div class="flex flex-row items-center justify-center">
            <button
                type="button"
                onclick={() => {
                    pres_mgmt_loc.current.rpt__session_no_bio =
                        !pres_mgmt_loc.current.rpt__session_no_bio;

                    qry__trigger = true;
                    rpt__name = 'session_no_bio';
                }}
                class="ae_btn_info btn-sm m-1">
                {#if pres_mgmt_loc.current.rpt__session_no_bio}
                    <ToggleRight size="1em" class="m-1" />
                    With
                {:else}
                    <ToggleLeft size="1em" class="m-1" />
                    Without
                {/if}
            </button>
        </div>
    </header>
{/if}

<!-- Show sessions that have POC agreed to terms -->
{#if rpt__name == 'sessions_poc_agree'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else if pres_mgmt_loc.current.rpt__session_poc_agree}
                <Check size="1em" class="m-1" />
            {:else}
                <X size="1em" class="m-1" />
            {/if}
            Sessions POC
            {#if pres_mgmt_loc.current.rpt__session_poc_agree}
                Agreed
            {:else}
                Not Agreed
            {/if}
        </h3>

        <div
            class="flex flex-row items-center justify-center"
            class:hidden={!$ae_loc.edit_mode}>
            <button
                type="button"
                onclick={() => {
                    pres_mgmt_loc.current.rpt__session_poc_agree =
                        !pres_mgmt_loc.current.rpt__session_poc_agree;

                    qry__trigger = true;
                    rpt__name = 'sessions_poc_agree';
                }}
                class="ae_btn_info btn-sm m-1"
                title="Toggle to show sessions with or without POC agreement to terms">
                {#if pres_mgmt_loc.current.rpt__session_poc_agree}
                    <ToggleRight size="1em" class="m-1" />
                    With
                {:else}
                    <ToggleLeft size="1em" class="m-1" />
                    Without (NOT working)
                {/if}
            </button>
        </div>
    </header>
{/if}

{#if event_session_obj_li}
    <Comp_event_session_obj_tbl
        link_to_type="event"
        link_to_id={$events_slct.event_id}
        bind:event_session_obj_li
        {hide_session_code}
        {log_lvl}></Comp_event_session_obj_tbl>
{/if}
