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

    event_file_obj_li?: any[];

    rpt__name?: string;
    rpt__sort?: string;
    // rpt__order_by_li?: any;
    rpt__enabled?: string;
    rpt__hidden?: string;
    rpt__view?: 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_file_obj_li = $bindable([]),

    rpt__name = $bindable('event_files'), // event_files, recent_files, large_files
    rpt__sort = $bindable('created_on'), // updated_on, start_datetime
    // rpt__order_by_li = $bindable({'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC', 'filename': 'ASC', 'extension': 'ASC', 'hosted_file_size': 'ASC'}),
    rpt__enabled = $bindable('all'), // enabled, disabled, all
    rpt__hidden = $bindable('all'), // hidden, not_hidden, all
    rpt__view = $bindable('alt'),
    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_file_obj_tbl from '../../../ae_comp__event_file_obj_tbl_wrapper.svelte';
import { ArrowUpDown, List, LoaderCircle } from '@lucide/svelte';
let ae_promises: key_val = $state({});

let rpt__order_by_li: key_val = $state({});

let sort_option_kv: key_val = {
    created_on: {
        name: 'Created On',
        field_kv: {
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC',
            filename: 'ASC',
            extension: 'ASC',
            hosted_file_size: 'ASC'
        }
    },
    updated_on: {
        name: 'Updated On',
        field_kv: {
            priority: 'DESC',
            sort: 'DESC',
            updated_on: 'DESC',
            created_on: 'DESC',
            filename: 'ASC',
            extension: 'ASC',
            hosted_file_size: 'ASC'
        }
    },
    filename_asc: {
        name: 'Filename',
        field_kv: {
            filename: 'ASC',
            extension: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    },
    filename_desc: {
        name: 'Filename',
        field_kv: {
            filename: 'DESC',
            extension: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    },
    file_type: {
        name: 'Extension/Type',
        field_kv: {
            extension: 'ASC',
            filename: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    },
    file_size: {
        name: 'File Size',
        field_kv: {
            hosted_file_size: 'DESC',
            filename: 'ASC',
            extension: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    },
    start_datetime_asc: {
        name: 'Start Date Time',
        field_kv: {
            event_session_start_datetime: 'ASC',
            event_session_name: 'ASC',
            filename: 'ASC',
            extension: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    },
    start_datetime_desc: {
        name: 'Start Date Time',
        field_kv: {
            event_session_start_datetime: 'DESC',
            event_session_name: 'ASC',
            filename: 'ASC',
            extension: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC',
            updated_on: 'DESC'
        }
    }
};

$effect(() => {
    if (qry__trigger) {
        if (log_lvl) {
            console.log(
                `Report: ${rpt__name}; Triggered query for event files.`
            );
        }
        qry__trigger = false;

        rpt__order_by_li =
            sort_option_kv[pres_mgmt_loc.current.qry__files_sort]?.field_kv ??
            sort_option_kv['created_on'].field_kv;

        if (rpt__name == 'recent_files') {
            handle_qry__event_file({
                created_on_offset:
                    pres_mgmt_loc.current.qry__files_offset_seconds,
                // min_file_size: pres_mgmt_loc.current.qry__files_min_size,
                file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                // ft_search_str: '',
                // lk_search_str: '',
                limit: rpt__limit,
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else if (rpt__name == 'large_files') {
            handle_qry__event_file({
                created_on_offset: null,
                min_file_size: pres_mgmt_loc.current.qry__files_min_size,
                file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                // ft_search_str: '',
                // lk_search_str: '',
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else if (rpt__name == 'event_files') {
            handle_qry__event_file({
                created_on_offset:
                    pres_mgmt_loc.current.qry__files_offset_seconds,
                min_file_size: pres_mgmt_loc.current.qry__files_min_size,
                file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                limit: rpt__limit,
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else {
            console.log(`Unknown report name: ${rpt__name}`);
        }
    }
});

async function handle_qry__event_file({
    created_on_offset = null,
    min_file_size = null, // in bytes
    file_purpose = null,
    // ft_search_str = '',
    // lk_search_str = '',
    enabled = rpt__enabled,
    hidden = rpt__hidden,
    view = rpt__view,
    limit = rpt__limit,
    order_by_li = rpt__order_by_li,
    log_lvl = 0
}: {
    created_on_offset?: string | number | null;
    min_file_size?: number | null;
    file_purpose?: string | null;
    // ft_search_str?: string,
    // lk_search_str?: string,
    enabled?: 'enabled' | 'all' | 'not_enabled' | string;
    hidden?: 'hidden' | 'all' | 'not_hidden' | string;
    view?: string;
    limit?: number;
    order_by_li?: any;
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log('handle_qry__event_file()');
    }

    $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_file_obj_li = [];
    $events_slct.event_file_obj_li = []; // Clear out any previous results.
    event_file_obj_li = [];

    let created_on_str = null;
    if (created_on_offset) {
        // Calculate the datetime to pass based on the selected offset.
        let offset = Number(created_on_offset) ?? 0;

        let current_datetime = new Date();
        console.log(`Current time:`, current_datetime);

        // It is very important to know that all of the created_on and updated_on timestamps are in ET timezone. Sorry...?
        let for_et_tz_datetime = new Date(
            current_datetime.toLocaleString('en-US', {
                timeZone: 'America/New_York'
            })
        );
        const adjust_minutes = for_et_tz_datetime.getTimezoneOffset(); // Usually 240 minutes for ET.
        const adjusted_for_et_tz_datetime = new Date(
            for_et_tz_datetime.getTime() - adjust_minutes * 60 * 1000
        );
        const adjusted_for_et_tz_datetime_iso_str = adjusted_for_et_tz_datetime
            .toISOString()
            .slice(0, -1);
        console.log(
            `Adjusted for ET TZ time:`,
            adjusted_for_et_tz_datetime_iso_str
        );

        let offset_datetime = adjusted_for_et_tz_datetime;
        offset_datetime.setSeconds(offset_datetime.getSeconds() - offset);
        console.log(`Offset time:`, offset_datetime);
        // .slice(0, 19).replace('T', ' '), // '2024-10-15 13:59:59'
        const offset_datetime_iso_str = adjusted_for_et_tz_datetime
            .toISOString()
            .slice(0, -1);
        console.log(`Offset time ET ISO: ${offset_datetime_iso_str}`);

        created_on_str = offset_datetime_iso_str;

        // Convert to US Eastern time and output as ISO string.
        // let offset_datetime_local = new Date(offset_datetime.toLocaleString('en-US', {timeZone: 'America/New_York'}));
        // console.log(`Test time local ET: ${offset_datetime_local}`);

        // let formatted_str = offset_datetime_local.toLocaleString('en-US', {
        //     year: 'numeric',
        //     month: '2-digit',
        //     day: '2-digit',
        //     hour: '2-digit',
        //     minute: '2-digit',
        //     second: '2-digit',
        //     timeZone: 'UTC'
        //     });
        // console.log(`Test time local ET: ${formatted_str}`);

        // let offset_datetime_local_str = offset_datetime_local.toISOString();
        // console.log(`Test time local ET: ${offset_datetime_local_str}`);

        // created_on_str = offset_datetime_local_str;
    }

    ae_promises.search__event_file = events_func
        .qry__event_file({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            qry_created_on: created_on_str,
            qry_min_file_size: min_file_size,
            qry_file_purpose: file_purpose,
            enabled: enabled as any,
            hidden: hidden as any,
            view: view,
            limit: limit,
            order_by_li: order_by_li,
            // try_cache: try_cache,
            log_lvl: log_lvl
        })
        .then(function (search_results) {
            // Processing the results from the search.
            if (!search_results) {
                search_results = [];
            }
            $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_file_obj_li = search_results;
            // $events_slct.event_file_obj_li = search_results;
            event_file_obj_li = search_results;
            if (log_lvl) {
                console.log(event_file_obj_li);
            }
            // $events_sess.pres_mgmt.status_qry__search = 'done';
        })
        .finally(() => {
            if (log_lvl) {
                console.log(
                    'TEST SEARCH - Search done. Pulling out the event_file_ids.'
                );
            }
            // console.log(`TEST search: ${$lq_kv__event_file_obj_li}`);

            // event_file_id_li = [];

            // We need to loop through the array of objects and get the event_file_id from each object a new list of event_file_ids. 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.
            // for (let i = 0; i < $events_slct.event_file_obj_li.length; i++) {
            //     tmp_li.push($events_slct.event_file_obj_li[i].event_file_id);
            // }
            // event_file_id_li = tmp_li;

            // event_file_id_li = $events_slct.event_file_obj_li.map(file_obj => file_obj.event_file_id);

            // 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_file_id_li:`, event_file_id_li);
            //     // console.log(`TEST SEARCH - search live query: ${$lq_kv__event_file_obj_li}`);
            // }
        });
}
</script>

{#if rpt__name == 'event_files' || rpt__name == 'large_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}
                <List size="1em" class="m-1" />
            {/if}
            File Uploads
        </h3>

        <div class="flex flex-row items-center justify-center">
            <select
                class="select ae_btn_info m-1 inline-block w-40 px-1 text-sm"
                bind:value={pres_mgmt_loc.current.qry__files_offset_seconds}
                onchange={() => {
                    if (pres_mgmt_loc.current.qry__files_offset_seconds) {
                        // Calculate the datetime to pass based on the selected offset.
                        // let offset = pres_mgmt_loc.current.qry__files_offset_seconds ?? 0;
                        // let created_on = new Date()
                        // console.log(`Created on:`, created_on);
                        // created_on.setSeconds(created_on.getSeconds() - offset);
                        // handle_qry__event_file({
                        //     created_on_offset: pres_mgmt_loc.current.qry__files_offset_seconds ?? 0,
                        //     file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                        //     log_lvl: log_lvl,
                        // });
                        qry__trigger = true;
                    } else {
                        console.log('No offset is will be used.');
                        // handle_qry__event_file({
                        //     log_lvl: log_lvl,
                        // });
                        qry__trigger = true;
                    }

                    pres_mgmt_loc.current.show_report = 'event_files';
                }}>
                <option value="">-- offset not set --</option>
                <option value="600">10 minutes</option>
                <option value="1800">30 minutes</option>
                <option value="3600">1 hour</option>
                <option value="10800">2 hours</option>
                <option value="21600">6 hours</option>
                <option value="43200">12 hours</option>
                <option value="86400">24 hours</option>
                <option value="129600">36 hours</option>
                <option value="172800">48 hours</option>
                <option value="259200">72 hours</option>
                <option value="604800">1 week</option>
                <option value="1209600">2 weeks</option>
                <option value="2419200">4 weeks</option>
                <option value="7776000">12 weeks</option>
                <option value="15552000">24 weeks</option>
            </select>

            <select
                class="select ae_btn_info m-1 inline-block w-40 px-1 text-sm"
                bind:value={pres_mgmt_loc.current.qry__files_min_size}
                onchange={() => {
                    // handle_qry__event_file({
                    //     min_file_size: pres_mgmt_loc.current.qry__files_min_size ?? 100000000, // in bytes
                    //     file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                    //     log_lvl: log_lvl,
                    // });
                    qry__trigger = true;
                    pres_mgmt_loc.current.show_report = 'event_files';
                }}>
                <option value="">-- size not set --</option>
                <option value="10000000">10 MB</option>
                <option value="25000000">25 MB</option>
                <option value="50000000">50 MB</option>
                <option value="75000000">75 MB</option>
                <option value="100000000">100 MB</option>
                <option value="150000000">150 MB</option>
                <option value="250000000">250 MB</option>
                <option value="500000000">500 MB</option>
                <option value="1000000000">1 GB</option>
                <!-- <option value="5000000000">5 GB</option> -->
            </select>

            <select
                id="file_purpose"
                name="file_purpose"
                class="select ae_btn_info m-1 inline-block w-40 p-1 text-sm"
                bind:value={pres_mgmt_loc.current.qry__file_purpose}
                onchange={() => {
                    // handle_qry__event_file({
                    //     min_file_size: pres_mgmt_loc.current.qry__files_min_size ?? 100000000, // in bytes
                    //     file_purpose: pres_mgmt_loc.current.qry__file_purpose ?? null,
                    //     log_lvl: 1,
                    // });
                    qry__trigger = true;
                    pres_mgmt_loc.current.show_report = 'event_files';
                }}>
                <option
                    value={null}
                    selected={!pres_mgmt_loc.current.qry__file_purpose}
                    class="text-xs">
                    -- purpose not set --
                </option>
                {#if pres_mgmt_loc.current.file_purpose_option_kv}
                    {#each Object.entries(pres_mgmt_loc.current.file_purpose_option_kv) as [key, file_purpose_option] (key)}
                        <option
                            value={key}
                            selected={pres_mgmt_loc.current.qry__file_purpose === key}>
                            {(file_purpose_option as any)?.name}
                        </option>
                    {/each}
                {/if}
            </select>

            <label class="label text-sm">
                <ArrowUpDown size="1em" class="m-1" />
                Sort by:

                <select
                    class="select ae_btn_info m-1 inline-block w-44 px-1 text-sm"
                    bind:value={pres_mgmt_loc.current.qry__files_sort}
                    onchange={(event) => {
                        if ((event.target as HTMLInputElement).value) {
                            // rpt__sort = (event.target as HTMLInputElement).value;
                            pres_mgmt_loc.current.qry__files_sort = (
                                event.target as HTMLInputElement
                            ).value;
                        } else {
                            // rpt__sort = 'created_on';
                            pres_mgmt_loc.current.qry__files_sort =
                                'created_on';
                        }

                        // rpt__order_by_li = sort_option_kv[rpt__sort]?.field_kv ?? sort_option_kv['created_on'].field_kv;
                        rpt__order_by_li =
                            sort_option_kv[
                                pres_mgmt_loc.current.qry__files_sort
                            ]?.field_kv ??
                            sort_option_kv['created_on'].field_kv;

                        // ae_promises.handle_search__event_presenter = handle_search__event_presenter({
                        //     // ft_search_str: '',
                        //     // lk_search_str: '',
                        //     order_by_li: pres_mgmt_loc.current.qry__presenter_order_by_li,
                        //     log_lvl: log_lvl,
                        // });
                        qry__trigger = true;
                        pres_mgmt_loc.current.show_report = 'event_files';
                    }}>
                    <option value="created_on">Add/Uploaded On</option>
                    <option value="filename_asc">Filename ASC</option>
                    <option value="filename_desc">Filename DESC</option>
                    <option value="file_type">File Type/Ext</option>
                    <option value="file_size">File Size</option>
                    <option
                        value="updated_on"
                        class:hidden={!$ae_loc.administrator_access}
                        >Updated On</option>
                    <option value="start_datetime_asc"
                        >Start Date Time ASC</option>
                    <option value="start_datetime_desc"
                        >Start Date Time DESC</option>
                    <!-- <option value="created_on">Created On</option> -->
                    <!-- <option value="sort">Sort</option> -->
                    <!-- <option value="priority">Priority</option> -->
                </select>
            </label>
        </div>
    </header>
{/if}

{#if event_file_obj_li}
    <!-- bind:show_direct_download={pres_mgmt_loc.current.show__direct_download} -->
    <Comp_event_file_obj_tbl
        bind:event_file_obj_li
        show_location_fields={true}
        show_presentation_fields={true}
        show_session_fields={true}
        bind:show_direct_download={pres_mgmt_loc.current.show__direct_download}
        {hide_session_code}></Comp_event_file_obj_tbl>
{/if}
