<script lang="ts">
export let data;
console.log(`ae_ Svelte Events Speakers +page data:`, data);

import { onMount } from 'svelte';


// https://github.com/skeletonlabs/skeleton/blob/master/packages/skeleton/src/lib/utilities/Modal/types.ts
// 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 { ae_util } from '$lib/ae_utils';
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 ae_modal_scrollfix'} };

const modal_edit__event_presenter_obj: ModalSettings = {
	type: 'component',
	component: modalComponentEditEventPresenterObj,
    title: 'Speaker Form', // Editing Event Presenter
    position: '', // default is "items-center"

    response: (r: boolean | undefined) => handle_modal_close(r)
};

// Viewing
const modalComponentViewEventPresenterObj: ModalComponent = { ref: View_modal_event_presenter_obj, props: {container_class_li: 'w-full p-4 space-y-4 card ae_modal_scrollfix'} };

const modal_view__event_presenter_obj: ModalSettings = {
    type: 'component',
    component: modalComponentViewEventPresenterObj,
    title: 'Speaker Submission', // Viewing 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
    // },

    response: (r: boolean | undefined) => handle_modal_close(r)
};

// This function waits for the response from one of the modals. Do stuff when the modal is closed.
function handle_modal_close(response: boolean | undefined) {
    console.log('Modal closed. Response:', response);

    ae_util.handle_url_and_message('event_presenter_id', null);

    // We do NOT want to keep these values if it is closed and not just switching from view to edit. A "smart" transition?
    if (!$ae_loc.mod.events.show_edit__event_presenter_obj || !$ae_loc.mod.events.show_view__event_presenter_obj) {
        console.log('Clearing event_presenter_id and event_presenter_obj');
        $slct.event_presenter_id = null;

        if ($slct.event_presenter_obj) {
            console.log('Clearing event_presenter_obj');
            $slct.event_presenter_obj = null;
        }
    } else {
        console.log('Not clearing event_presenter_id and event_presenter_obj');
        console.log(`show_edit__event_presenter_obj: ${$ae_loc.mod.events.show_edit__event_presenter_obj}`);
        console.log(`show_view__event_presenter_obj: ${$ae_loc.mod.events.show_view__event_presenter_obj}`);
    }
}


$ae_loc.hostname = data.url.hostname;
$ae_loc.site_domain = data.url.origin;

// 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.events.show_view__event_presenter_obj = false;
if ($ae_loc.trusted_access) {
    $ae_loc.mod.events.show_list__event_presenter_obj_li = true;
} else {
    $ae_loc.mod.events.show_list__event_presenter_obj_li = false;
}

let ae_event_id_get_promise: Promise<any>;
let ae_event_presenter_obj_li_get_promise: Promise<any>;
let ae_event_presenter_obj_get_promise: Promise<any>;


// This might need to be reviewed and compared to sponsorships version again
if ($ae_loc.mod.events.event_id) {
    $slct.event_id = $ae_loc.mod.events.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});
}


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);

    // $slct_trigger = 'msg_parent';
    ae_util.handle_url_and_message('event_id', $slct.event_id);
    ae_util.handle_url_and_message('event_presenter_id', $slct.event_presenter_id);
    if ($slct.event_presenter_id) {
        console.log(`Got an ID. Let's clear the modal store just in case!`);
        modalStore.clear();
        // console.log(`Got an ID. Let's show the modal!`);
        // modalStore.trigger(modal_edit__event_presenter_obj);
        // $slct_trigger = 'load__event_presenter_obj';
    }
});


$: 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;

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

        let message = {'event_presenter_id': $slct.event_presenter_id};
        window.parent.postMessage(message, "*");
        // console.log('Message sent to parent (iframe):', message);
    }

    // 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);

    let message = {'event_presenter_id': $slct.event_presenter_id};
    window.parent.postMessage(message, "*");
    // console.log('Message sent to parent (iframe):', message);
}


$: 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;

	// 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});
}

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: 1
        })

    .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;
}



// handle_load_ae_obj_li__event() was done in layout.ts
// This is different from how the sponsorships are loaded.
// Do we need anything from the event object to load the presenters?



// 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});
}


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: 1
        })
    .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;

}







// // let delete_event_presenter_obj_promise: Promise<any>;
// let delete_event_presenter_obj_promise;
// async function handle_delete_event_presenter_obj({event_presenter_id, hosted_file_id=null, method='delete'}) {
//     console.log('*** handle_delete_event_presenter_obj() ***');

//     // if (hosted_file_id) {
//     //     let delete_hosted_file_obj_promise = api.delete_hosted_file({
//     //         api_cfg: $ae_api,
//     //         hosted_file_id: hosted_file_id,
//     //         link_to_type: 'event_presenter',
//     //         link_to_id: event_presenter_id,
//     //         rm_orphan: true,
//     //         // params: params,
//     //         key: $ae_api.api_crud_super_key,
//     //         log_lvl: 2
//     //         })
//     //     .then(function (hosted_file_obj_delete_result) {
//     //         if (hosted_file_obj_delete_result) {
//     //             // console.log(`Result:`, hosted_file_obj_delete_result);

//     //             dispatch(
//     //                 'deleted__hosted_file_obj',
//     //                 {
//     //                     hosted_file_id: hosted_file_id,
//     //                 }
//     //             );
//     //         }
//     //     })
//     //     .catch(function (error) {
//     //         console.log('The result was null or false when trying to delete.', error);
//     //     });
//     // }

//     delete_event_presenter_obj_promise = api.delete_ae_obj_id_crud({
//         api_cfg: $ae_api,
//         obj_type: 'event_presenter',
//         obj_id: event_presenter_id,
//         method: method,
//         // params: params,
//         key: $ae_api.api_crud_super_key,
//         log_lvl: 0
//         })
//     .then(function (event_presenter_obj_delete_result) {
//         if (event_presenter_obj_delete_result) {
//             // console.log(`Result:`, event_presenter_obj_delete_result);

//         }
//     })
//     .catch(function (error) {
//         console.log('The result was null or false when trying to delete.', error);
//     });

//     return delete_event_presenter_obj_promise;
// }


</script>


<section class="ae_events_speakers md:container h-full mx-auto flex flex-col items-center space-y-4">

<header>
    <h1 class="h2">
        <!-- &AElig; - Events: Speakers -->
        Speaker Hub
    </h1>
</header>

<section>
    <button
        class="btn variant-ghost-primary"
        on:click={() => {
            // $ae_loc.mod.events.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.show_edit__event_presenter_obj = true;
            $slct_trigger = 'show_edit__event_presenter_obj';
        }}
        >
        <span class="fas fa-edit mx-1"></span>
        Start Speaker Submission Form
    </button>
</section>

<section class="events_speakers_list ae_h_scrollfix">
    {#await ae_event_presenter_obj_li_get_promise}
        <span class="fas fa-spinner fa-spin"></span>
        <span class="loading-text">
            Loading...
        </span>
    {/await}

    {#if $slct.event_presenter_obj_li && $ae_loc.mod.events.show_list__event_presenter_obj_li}
    <List_event_presenter_obj class_li=""/>
    {/if}
</section>

</section>


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