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




// 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, slct, slct_trigger } from '$lib/ae_stores';

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

type key_val = {
    [key: string]: any;
};

// 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',
    position: '', // default is "items-center"

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

function handle_modal_close(response: boolean | undefined) {
    console.log('Modal closed. Response:', response);

    let location = window.location.href;
    const url = new URL(location);
    url.searchParams.delete('sponsorship_id');
    history.pushState({}, '', url);

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

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;


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

let ae_sponsorship_cfg_obj_get_promise;

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 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');
$slct_trigger = 'load__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);
}

let ae_sponsorship_obj_get_promise;

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


</script>


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

{#if $ae_loc.ds.hub__page__sponsorships__create_info}
{@html $ae_loc.ds.hub__page__sponsorships__create_info}
{:else}

<header>
    <h1 class="h1">Information Goes Here</h1>
</header>

<section>
        <div class="alert alert-info">
            More information goes here.
        </div>
</section>

{/if}

<!-- <section class="btn btn-group"> -->
    <button
        class="btn variant-ghost-primary"
        on:click={() => {
            // $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>
<!-- </section> -->

</section>
