<script lang="ts">
export let data;
console.log(`ae_ Svelte Sponsorships [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';
import type { key_val } from '$lib/ae_stores';

import Edit_modal_sponsorship_obj from '../10_edit_modal__sponsorship_obj.svelte';


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

const modal_edit__sponsorship_obj: ModalSettings = {
	type: 'component',
	component: modalComponentEditSponsorshipObj,
    title: 'Edit Your Sponsorship 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('sponsorship_id', null);

    // We want to keep these values in case they want to re-open the modal. Do NOT clear.
    // $slct.sponsorship_id = null;
    // $slct.sponsorship_obj = null;
}

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

    let message = {'sponsorship_cfg_id': $slct.sponsorship_cfg_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.sponsorships.show_edit__sponsorship_obj = false;
$ae_loc.mod.sponsorships.show_view__sponsorship_obj = false;

let ae_sponsorship_obj_get_promise: Promise<any>;
let ae_sponsorship_cfg_obj_get_promise;


onMount(() => {
    console.log('Sponsorships [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('sponsorship_cfg_id', $slct.sponsorship_id);
    ae_util.handle_url_and_message('sponsorship_id', $slct.sponsorship_id);
    if ($slct.sponsorship_id) {
        console.log(`Got an ID. Let's show the modal!`);
        // This causes a problem frequently... See through...
        // modalStore.trigger(modal_edit__sponsorship_obj);
    } 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 Sponsorship Cfg Obj with ID based on the URL param.
$slct.sponsorship_cfg_id = data.url.searchParams.get('sponsorship_cfg_id');
$slct_trigger = 'load__sponsorship_cfg_obj';


$: if ($slct_trigger == 'load__sponsorship_cfg_obj' && $slct.sponsorship_cfg_id) {
    console.log('Selected Sponsorship Cfg ID:', $slct.sponsorship_cfg_id);

    $slct_trigger = null;

    handle_load_ae_obj_id__sponsorship_cfg({sponsorship_cfg_id: $slct.sponsorship_cfg_id, try_cache: false});
}

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

    let params = {};

	// $ae_loc.hub.sponsorship_cfg_id_qry_status = 'loading';
    ae_sponsorship_cfg_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship_cfg',
        obj_id: sponsorship_cfg_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 (sponsorship_cfg_obj_get_result) {
        if (sponsorship_cfg_obj_get_result) {
            $slct.sponsorship_cfg_obj = sponsorship_cfg_obj_get_result;
            console.log(`sponsorship_cfg object:`, $slct.sponsorship_cfg_obj);
        }

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

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

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

    return ae_sponsorship_cfg_obj_get_promise;
}


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

    // $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
    // $slct_trigger = 'show_edit__sponsorship_obj';
}


$: if ($slct_trigger == 'load__sponsorship_obj' && $slct.sponsorship_id) {
    console.log('Selected Sponsorship ID:', $slct.sponsorship_id);

    $slct_trigger = null;

    handle_load_ae_obj_id__sponsorship({sponsorship_id: $slct.sponsorship_id, try_cache: false});

    // modalStore.trigger(modal_edit__sponsorship_obj);
    // $slct_trigger = 'show_edit__sponsorship_obj';
}

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

    let params = {};

	// $ae_loc.hub.sponsorship_id_qry_status = 'loading';
    ae_sponsorship_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship',
        obj_id: sponsorship_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 (sponsorship_obj_get_result) {
        if (sponsorship_obj_get_result) {
            $slct.sponsorship_obj = sponsorship_obj_get_result;
            console.log(`sponsorship object:`, $slct.sponsorship_obj);
        }

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

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

    return ae_sponsorship_obj_get_promise;
}

let testing = false;

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

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

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

    // modalStore.clear();
    modalStore.trigger(modal_edit__sponsorship_obj);
}
</script>


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

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


<section>
{#if $slct.sponsorship_id}

<div class="text-center m-4">
{#if $slct.sponsorship_obj}
<p class="font-bold">Welcome to the Sponsor Hub {$slct.sponsorship_obj.name}!</p>
{:else}
<p>Welcome to the Sponsor Hub!</p>
{/if}
</div>

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


        // $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
        // $slct_trigger = 'load__sponsorship_obj';
        // $slct_trigger = 'show_edit__sponsorship_obj';
        // modalStore.trigger(modal_edit__sponsorship_obj);
        // $ae_trig.m_sponsorships__show_modal_edit = true;
    }}
    >
    <span class="fas fa-edit mx-1"></span>
    Edit Sponsor {$slct.sponsorship_id}
</button>
{:else}
<button
    class="btn variant-ghost-primary w-96"
    on:click={() => {
        ae_util.handle_url_and_message('sponsorship_id', null);
        modalStore.trigger(modal_edit__sponsorship_obj);

        // $slct_trigger = 'load__sponsorship_obj';

        $slct_trigger = 'show_edit__sponsorship_obj';
        $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;

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


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


</section>
