<script lang="ts">
/** @type {import('./$types').PageData} */
export let data: any;
// console.log(`ae_core root +page.svelte data:`, data);

// import { onMount } from 'svelte';
import { goto, invalidate, pushState, replaceState } from '$app/navigation';

// import { clipboard, FileDropzone, getModalStore, localStorageStore, ProgressRadial, RadioGroup, RadioItem, TabGroup, Tab, TabAnchor } from '@skeletonlabs/skeleton';

import type { key_val } from '$lib/ae_stores';
// import { ae_util } from '$lib/ae_utils';
// import { api } from '$lib/api';
// import Element_ae_crud from '$lib/element_ae_crud.svelte';
// import Element_data_store from '$lib/element_data_store_v2.svelte';
import Comp_person_obj_tbl from './ae_comp__person_obj_tbl.svelte';

// import { liveQuery } from "dexie";
import { core_func } from '$lib/ae_core_functions';
// import { db_core } from "$lib/db_core";
// import { db_events } from "$lib/db_events";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
// import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
// import { events_func } from '$lib/ae_events_functions';

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
$slct.account_id = data.account_id;
console.log(`$slct.account_id = `, $slct.account_id);
let ae_acct = data[$slct.account_id];
console.log(`ae_acct = `, ae_acct);


let person_id_random_li: string[] = [];

// let load_obj_li_results: Promise<any>|key_val;
// let search_submit_results: Promise<any>|key_val;

// async function handle_load_ae_obj_li__person() {
//     console.log(`handle_load_ae_obj_li__person()`);
//     $ae_trig['load__person_obj_li'] = null;

//     load_obj_li_results = core_func.handle_load_ae_obj_li__person({
//         api_cfg: $ae_api,
//         person_id_random_li: person_id_random_li,
//         log_lvl: 1
//     });

//     return load_obj_li_results;
// }



</script>


<section class="ae_core md:container h-full mx-auto">

<h2 class="h3">&AElig; Core for {$ae_loc.account_name ?? 'Æ loading...'}</h2>

<button
    type="button"
    on:click={() => {
        console.log('Edit the POC person for the session.');

        let params = {
            qry__limit: $ae_sess.person.qry_limit__people,
        }

        // $slct.person_obj_li = await core_func.handle_load_ae_obj_li__person({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

        let person_results = core_func.handle_load_ae_obj_li__person({
            api_cfg: $ae_api,
            account_id: $slct.account_id,
            params: params,
            log_lvl: 1
        })
        .then(function (load_results) {
            console.log(`Loaded person_obj_li:`, load_results);

            // We need to make this ready for the select option list. Convert the list to a key value pair with the person_id_random as the key. We also need to set the option text value to: full_name (primary_email)
            if (load_results) {
                $slct.person_id_random_li = load_results;

                person_id_random_li = [];

                let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

                for (let i = 0; i < $slct.person_id_random_li.length; i++) {
                    let person_obj = $slct.person_id_random_li[i];
                    let person_id_random = person_obj.person_id_random;
                    tmp_li.push(person_id_random);
                }
                person_id_random_li = tmp_li;



                // $slct.person_id_random_li = load_results.map((person_obj) => person_obj.person_id_random);
                // let person_obj_li = load_results;
                // let person_obj_kv = {};
                // person_obj_kv[''] = '-- Select a person --';
                // person_obj_li.forEach((person_obj) => {
                //     let option_text = `${person_obj.full_name} (${person_obj.primary_email})`;
                //     person_obj_kv[person_obj.person_id_random] = option_text;
                // });
                // $slct.person_obj_kv = person_obj_kv;
            }
            // $slct.person_obj_kv = $slct.person_obj_kv;
            // console.log(`$slct.person_obj_kv = `, $slct.person_obj_kv);

            return load_results;
        })
        .finally(() => {
            console.log(`person_id_random_li:`, person_id_random_li);
            $ae_sess.person.show_report__person_li = true;
        });
    }}
    class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
    >
    <span class="fas fa-user mx-1"></span>
    List People
</button>

<button
    type="button"
    on:click={async () => {
        console.log('Add Person');
        if (!confirm(`Add a new person to the account?\n${$ae_loc.account_name}\nID: ${$slct.account_id}`)) {
            return;
        }

        let person_data = {
            account_id_random: $slct.account_id,
            // user_id_random: user_obj.user_id_random,
            source_code: 'manual:SK-core',
            given_name: 'New',
            family_name: 'Person',
            // professional_title: 'Temp Prof Title',
            // affiliations: 'Temp Org',
            // primary_email: 'tmp+person@oneskyit.com',
            // allow_auth_key: false,
            auth_key: Math.floor(Math.random() * 90000000) + 10000000,
            // Random number between 100000 and 999999
            passcode: Math.floor(Math.random() * 900000) + 100000,
            enable: true,
        }

        let new_person_obj = await core_func.handle_create_ae_obj__person({
            api_cfg: $ae_api,
            // user_id: $ae_loc.user_id,
            data_kv: person_data,
            log_lvl: 1,
        })

        console.log('new_person_obj:', new_person_obj);

        if (confirm(`Person created:\n${new_person_obj.full_name} (${new_person_obj.primary_email ?? 'no email'})\nID: ${new_person_obj.person_id_random}\n\nView this person?`)) {
            // window.location.reload();
            // invalidateAll();
            goto(`/core/person/${new_person_obj.person_id_random}`, { replaceState: true });
            // pushState(`/core/person/${new_person_obj.person_id_random}`, { replace: true });
            // replaceState(`/core/person/${new_person_obj.person_id_random}`);
        }
    }}
    class:hidden={!$ae_loc.edit_mode}
    class="btn btn-sm variant-soft-warning hover:variant-filled-warning"
    >
    <span class="fas fa-plus mx-1"></span>
    Add Person
</button>



<!-- Show people for this account -->
{#if $ae_sess.person.show_report__person_li && person_id_random_li?.length > 0}
<h3 class="h4 text-center">Person Records</h3>

<label
    class="text-sm"
    for="qry_limit__people">Max results:

<select
    id="qry_limit__people"
    bind:value={$ae_sess.person.qry_limit__people}
    on:change={() => {
        core_func.handle_load_ae_obj_li__person({
            api_cfg: $ae_api,
            account_id: $slct.account_id,
            params: {
                'qry__enabled': 'enabled',
                'qry__hidden': 'not_hidden',
                'qry__limit': $ae_sess.person.qry_limit__people,},
            log_lvl: 1,
        })
        .then(function (load_results) {
            console.log(`Loaded person_obj_li:`, load_results);
            if (load_results) {
                $slct.person_id_random_li = load_results;

                person_id_random_li = [];

                let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

                for (let i = 0; i < $slct.person_id_random_li.length; i++) {
                    let person_obj = $slct.person_id_random_li[i];
                    let person_id_random = person_obj.person_id_random;
                    tmp_li.push(person_id_random);
                }
                person_id_random_li = tmp_li;
            }
            return load_results;
        })
    }}
    class="select max-w-20 text-sm"
    >
    <option value={25}>25</option>
    <option value={50}>50</option>
    <option value={75}>75</option>
    <option value={100}>100</option>
    <option value={250}>250</option>
    <option value={400}>400</option>
    <option value={500}>500</option>
</select>

</label>

<div class="">
<!-- Count: {person_id_random_li?.length} -->
<Comp_person_obj_tbl
    bind:person_id_random_li={person_id_random_li}
    show_user_fields={$ae_loc.administrator_access}
    >
</Comp_person_obj_tbl>
</div>
{/if}


</section>


<style lang="postcss">
</style>
