<script lang="ts">
export let data: any;

console.log(`ae_ Svelte Events Speakers [slug] +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 } 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, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import type { key_val } from '$lib/ae_stores';

import Edit_modal_event_presenter from '../10_edit_modal__event_presenter_obj.svelte';


// Editing
const modalComponentEditEventPresenterObj: ModalComponent = { ref: Edit_modal_event_presenter, props: {container_class_li: 'w-full p-4 space-y-4 card'} };

const modal_edit__event_presenter: ModalSettings = {
	type: 'component',
	component: modalComponentEditEventPresenterObj,
    title: 'Edit Speaker Submission',
    position: '', // default is "items-center"

    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 want to keep these values in case they want to re-open the modal. Do NOT clear.
    // $slct.event_presenter_id = null;
    // $slct.event_presenter_obj = null;
}

if ($slct_trigger == 'msg_parent' && $slct.event_id) {
    console.log(`Message parent with event_id ${$slct.event_id}`);
    $slct_trigger = null

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


$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 a modal.
$ae_loc.mod.events.show_edit__event_presenter_obj = false;
$ae_loc.mod.events.show_view__event_presenter_obj = false;

let ae_event_presenter_get_promise: Promise<any>;
let ae_event_obj_get_promise;


onMount(() => {
    console.log('Events Presenters [New/Edit]: +page.svelte');

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

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

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

    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 show the modal!`);
        // This causes a problem frequently... See through...
        // modalStore.trigger(modal_edit__event_presenter);
    } else {
        console.log(`No ID. Nothing to show.`);
    }
});
// console.log(`$ae_loc = `, $ae_loc);
// $ae_loc.href_url = url;
// console.log(`$ae_loc.href_url = `, $ae_loc.href_url);


// Load the Event Obj with ID based on the URL param.
// $slct.event_id = data.url.searchParams.get('event_id');
// $slct_trigger = 'load__event_obj';


// $: if ($slct_trigger == 'load__event_obj' && $slct.event_id) {
//     console.log('Selected Event ID:', $slct.event_id);

//     $slct_trigger = null;

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

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

    let params = {};

	// $ae_loc.hub.event_id_qry_status = 'loading';
    ae_event_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event',
        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.
        params: params,
        log_lvl: 0
        })
    .then(function (event_obj_get_result) {
        if (event_obj_get_result) {
            $slct.event_obj = event_obj_get_result;
            console.log(`event object:`, $slct.event_obj);
        }

        // Auto show the selected event_presenter ID
        // Is this pushState needed here?
        // Set the URL param "event_id" to the current event_presenter ID.
        // const url = new URL(location);
        // url.searchParams.set('event_id', $slct.event_id);
        // history.pushState({}, '', url);

        // Is this postMessage needed here?
        // let message = {'event_id': $slct.event_id};
        // window.parent.postMessage(message, "*");

        // modalStore.trigger(modal_view__event_obj);
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_event_obj_get_promise;
}


// Load the Event Presenter Obj with ID based on the URL param.
// $slct.event_presenter_id = data.url.searchParams.get('ae_id');
$slct.event_presenter_id = data.url.searchParams.get('event_presenter_id');
if ($slct.event_presenter_id) {
    console.log('Selected Event Presenter ID:', $slct.event_presenter_id);
    $slct_trigger = 'load__event_presenter';

    // $ae_loc.mod.events.show_edit__event_presenter_obj = true;
    // $slct_trigger = 'show_edit__event_presenter';
}


$: if ($slct_trigger == 'load__event_presenter' && $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
    });

    // modalStore.trigger(modal_edit__event_presenter);
    // $slct_trigger = 'show_edit__event_presenter';
}

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_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_get_result) {
        if (event_presenter_get_result) {
            $slct.event_presenter_obj = event_presenter_get_result;
            console.log(`event_presenter object:`, $slct.event_presenter);
        }

        // Auto show the selected event_presenter ID
        // Is this pushState needed here?
        // Set the URL param "event_presenter_id" to the current event_presenter ID.
        // const url = new URL(location);
        // url.searchParams.set('event_presenter_id', $slct.event_presenter_id);
        // history.pushState({}, '', url);

        // Is this postMessage needed here?
        // let message = {'event_presenter_id': $slct.event_presenter_id};
        // window.parent.postMessage(message, "*");
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_event_presenter_get_promise;
}

let testing = false;

// $: if ($slct_trigger == 'show_edit__event_presenter' && $ae_loc.mod.events.show_edit__event_presenter) {
$: if (testing) {
//  && $ae_loc.mod.events.show_edit__event_presenter
// $: if ($slct_trigger == 'show_edit__event_presenter') {
    console.log('Show Modal Edit');
    $slct_trigger = null;
    testing = false;
    // $ae_trig.m_events__show_modal_edit = false;

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


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

{#if $ae_loc.ds.hub__page__events_speakers__create_info_header}
{@html $ae_loc.ds.hub__page__events_speakers__create_info_header}
{:else}
<header>
    <h1 class="h2">Speaker Hub Info Goes Here</h1>
</header>
{/if}


<section>
{#if $slct.event_presenter_id}

<div class="text-center m-4">
{#if $slct.event_presenter_obj}
<p>Welcome to the Speaker Hub {$slct.event_presenter_obj.full_name}!</p>
{:else}
<p>Welcome to the Speaker Hub!</p>
{/if}
</div>

<button
    class="btn variant-ghost-primary w-96"
    on:click={() => {
        ae_util.handle_url_and_message('event_presenter_id', $slct.event_presenter_id);
        modalStore.trigger(modal_edit__event_presenter);


        // $ae_loc.mod.events.show_edit__event_presenter_obj = true;
        // $slct_trigger = 'load__event_presenter';
        // $slct_trigger = 'show_edit__event_presenter';
        // modalStore.trigger(modal_edit__event_presenter);
        // $ae_trig.m_events__show_modal_edit = true;
    }}
    >
    <span class="fas fa-edit mx-1"></span>
    Edit Speaker ({$slct.event_presenter_id})
</button>
{:else}
<button
    class="btn variant-ghost-primary w-96"
    on:click={() => {
        ae_util.handle_url_and_message('event_presenter_id', null);
        modalStore.trigger(modal_edit__event_presenter);

        // $slct_trigger = 'load__event_presenter';

        $slct_trigger = 'show_edit__event_presenter';
        $ae_loc.mod.events.show_edit__event_presenter_obj = true;

        // modalStore.trigger(modal_edit__event_presenter);
    }}
    >
    <span class="fas fa-edit mx-1"></span>
    Start Speaker Submission Form
</button>
{/if}
</section>


{#if $ae_loc.ds.hub__page__events_speakers__create_info}
{@html $ae_loc.ds.hub__page__events_speakers__create_info}
{:else}
<section>
    <div class="alert alert-info">
        More information can go here or this can be hidden.
    </div>
</section>
{/if}


</section>
