<script lang="ts">
import { onMount } from 'svelte';
export let data;
console.log(`Svelte Events - Speakers page data:`, data);

// import { localStorageStore } from '@skeletonlabs/skeleton';
// import type { Writable } from 'svelte/store';
// const store_current_page: Writable<string> = localStorageStore('store_current_page', 'start');

// To retrieve the store, getModalStore must be invoked at the top level of your component!
import { getDrawerStore, getModalStore, ProgressRadial } from '@skeletonlabs/skeleton';
import type {
    DrawerSettings,
    ModalSettings,
    ModalComponent,
    ModalStore
    } from '@skeletonlabs/skeleton';
const modalStore = getModalStore();

import { api } from '$lib/api';
import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/ae_stores';
import type { key_val } from '$lib/ae_stores';

import Edit_modal_event_presenter_obj from './10_edit_modal__event_presenter_obj.svelte';
import List_event_presenter_obj from './10_list__event_presenter_obj.svelte';
import View_modal_event_presenter_obj from './10_view_modal__event_presenter_obj.svelte';


// Editing
const modalComponentEditEventPresenterObj: ModalComponent = { ref: Edit_modal_event_presenter_obj, props: {container_class_li: 'w-full p-4 space-y-4 card', container_header_class_li: 'card-header text-2xl font-bold'} };

const modal_edit__event_presenter_obj: ModalSettings = {
	type: 'component',
	component: modalComponentEditEventPresenterObj,
    title: 'Edit Event Presenter',
    position: '', // default is "items-center"
};

// Viewing
const modalComponentViewEventPresenterObj: ModalComponent = { ref: View_modal_event_presenter_obj, props: {container_class_li: 'w-full p-4 space-y-4 card', container_header_class_li: 'card-header text-2xl font-bold'} };

const modal_view__event_presenter_obj: ModalSettings = {
    type: 'component',
    component: modalComponentViewEventPresenterObj,
    title: 'View Event Presenter',
    position: '', // default is "items-center"

    // Provide arbitrary classes to the backdrop and modal elements:
    // backdropClasses: '!bg-green-500',
    // modalClasses: 'w-modal-wide',
    // modalClasses: 'w-full',

    // Provide arbitrary metadata to your modal instance:
    // meta: {
        // component_root_classes: 'w-full',
        // fn: do_something_function
    // },
};

// We don't want the edit or view to show up by default. Maybe if we see an object ID param in the URL, we can show the view modal.
$ae_loc.mod.events.show_edit__event_presenter_obj = false;
$ae_loc.mod.sponsorships.show_view__event_presenter_obj = false;

$: if ($slct_trigger == 'show_edit__event_presenter_obj' && $ae_loc.mod.events.show_edit__event_presenter_obj) {
    console.log('Show Modal Edit');
    $slct_trigger = null;

    let location = window.location.href;
    const url = new URL(location);
    url.searchParams.set('event_presenter_id', $slct.event_presenter_id);
    history.pushState({}, '', url);

    // modalStore.clear();
    modalStore.trigger(modal_edit__event_presenter_obj);
}
$: if ($slct_trigger == 'show_view__event_presenter_obj' && $ae_loc.mod.events.show_view__event_presenter_obj) {
    console.log('Show Modal View');
    $slct_trigger = null;

    let location = window.location.href;
    const url = new URL(location);
    url.searchParams.set('event_presenter_id', $slct.event_presenter_id);
    history.pushState({}, '', url);

    // modalStore.clear();
    modalStore.trigger(modal_view__event_presenter_obj);
}


if ($slct.event_id && !$slct.event_presenter_obj_li) {
    console.log(`No presenter list was found for Event ID: ${$slct.event_id}`);

    $slct_trigger = 'load__event_presenter_obj_li';
}

onMount(() => {
    console.log('Events - Speakers: +page.svelte');

    // console.log(`$ae_loc = `, $ae_loc);

	let href_url = window.location.href;
	// console.log(href_url);

    $ae_loc.href_url = href_url;
    // console.log(`$ae_loc.href_url = `, $ae_loc.href_url);
});


$: if ($slct_trigger == 'load__event_presenter_obj_li' && $slct.event_id) {
    console.log(`load__event_presenter_obj_li event_id: ${$slct.event_id}`);

    $slct_trigger = null;

    // $slct.event_id = $ae_loc.event_id;
	// handle_load_ae_obj_id__event({event_id: $slct.event_id, try_cache: false});
    handle_load_ae_obj_li__event_presenter({event_id: $slct.event_id, try_cache: false});
}


let ae_event_presenter_obj_li_get_promise: Promise<any>;

async function handle_load_ae_obj_li__event_presenter({event_id, try_cache=true}) {
    console.log('*** handle_load_ae_obj_li__event_presenter() ***');
    // console.log($ae_loc.mod.events);

    let enabled = $ae_loc.mod.events.enabled;
    let hidden = $ae_loc.mod.events.hidden;
    let limit = $ae_loc.mod.events.limit;
    let offset = $ae_loc.mod.events.offset;

    let params = {};

    let params_json: key_val = {};

    // console.log('params_json:', params_json);
    // console.log(params_json);

    $ae_loc.mod.events.qry_status = 'loading';
    ae_event_presenter_obj_li_get_promise = api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event_presenter',
        for_obj_type: 'event',
        for_obj_id: event_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        enabled: enabled,
        hidden: hidden,
        order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'updated_on': 'DESC', 'created_on': 'DESC'},
        // order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 0
        })

    .then(function (event_presenter_obj_li_get_result) {
        if (event_presenter_obj_li_get_result) {
            $slct.event_presenter_obj_li = event_presenter_obj_li_get_result;
        } else {
            $slct.event_presenter_obj_li = [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        $ae_loc.mod.events.qry_status = 'done';
        console.log('Object list:', $slct.event_presenter_obj_li);
    });

    return ae_event_presenter_obj_li_get_promise;
}


// Load the Event Presenter Obj with ID based on the URL param.
$: if ($slct_trigger == 'load__event_presenter_obj' && $slct.event_presenter_id) {
    console.log('Selected Event Presenter ID:', $slct.event_presenter_id);

    $slct_trigger = null;

    handle_load_ae_obj_id__event_presenter({event_presenter_id: $slct.event_presenter_id, try_cache: false});
}

let ae_event_presenter_obj_get_promise: Promise<any>;

async function handle_load_ae_obj_id__event_presenter({event_presenter_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__event_presenter() *** event_presenter_id=${event_presenter_id}`);

    let params = {};

    // $ae_loc.hub.event_presenter_id_qry_status = 'loading';
    ae_event_presenter_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event_presenter',
        obj_id: event_presenter_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (event_presenter_obj_get_result) {
        if (event_presenter_obj_get_result) {
            $slct.event_presenter_obj = event_presenter_obj_get_result;
            console.log(`event presenter object:`, $slct.event_presenter_obj);
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_event_presenter_obj_get_promise;

}

</script>


<div class="container h-full mx-auto items-center">
    <div class="space-y-10 flex flex-col">

        <h1 class="h1 text-center">&AElig; - Events: Speakers</h1>
        <section>
            <button
                class="btn variant-ghost-primary"
                on:click={() => {
                    // $ae_loc.mod.events_speakers.show_edit__event_presenter_obj = true;
                    $slct.event_presenter_id = null;
                    $slct.event_presenter_obj = null;

                    // modalStore.trigger(modal_edit__event_presenter_obj);
                    $ae_loc.mod.events_speakers.show_edit__event_presenter_obj = true;
                    $slct_trigger = 'show_edit__event_presenter_obj';
                }}
                >
                <span class="fas fa-edit mx-1"></span>
                Start/Edit Speaker
            </button>
        </section>

		<section class="events_speakers_list">

            <List_event_presenter_obj />

            <!-- {#if $slct.event_presenter_obj_li && $slct.event_presenter_obj_li.length}

            {#each $slct.event_presenter_obj_li as ae_event_presenter_obj, index}
                <div class="event_presenter_obj">
                    {ae_event_presenter_obj.given_name}
                </div>

            {/each}

            {/if} -->

        </section>
	</div>
</div>


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