<script lang="ts">
import { onMount } from 'svelte';
export let data;
console.log(`Svelte Sponsorships 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');

// 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 type { key_val } from '$lib/ae_stores';

import Edit_modal_sponsorship_obj from './10_edit_modal__sponsorship_obj.svelte';
import List_sponsorship_obj from './10_list__sponsorship_obj.svelte';
import View_modal_sponsorship_obj from './10_view_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', container_header_class_li: 'card-header text-2xl font-bold'} };

const modal_edit__sponsorship_obj: ModalSettings = {
	type: 'component',
	component: modalComponentEditSponsorshipObj,
    title: 'Edit Sponsorship',
    position: '', // default is "items-center"

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

// Viewing
const modalComponentViewSponsorshipObj: ModalComponent = { ref: View_modal_sponsorship_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__sponsorship_obj: ModalSettings = {
	type: 'component',
	component: modalComponentViewSponsorshipObj,
    title: 'Viewing Sponsorship',
    position: '', // default is "items-center"

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

    // Provide arbitrary metadata to your modal instance:
    // meta: { fn: do_something_function }

    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('event_presenter_id');
    history.pushState({}, '', url);
}

// 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.sponsorships.show_edit__sponsorship_obj = false;
$ae_loc.mod.sponsorships.show_view__sponsorship_obj = false;

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

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

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

    // $ae_loc.mod.sponsorships.show_view__sponsorship_obj = false;
    // modalStore.clear();
    modalStore.trigger(modal_edit__sponsorship_obj);
}
$: if ($slct_trigger == 'show_view__sponsorship_obj' && $ae_loc.mod.sponsorships.show_view__sponsorship_obj) {
    console.log('Show Modal View');
    $slct_trigger = null;

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

    // $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = false;
    // modalStore.clear();
    modalStore.trigger(modal_view__sponsorship_obj);
}


let ae_account_obj_get_promise;
let ae_sponsorship_obj_li_get_promise;

onMount(() => {
    console.log('Sponsorships: +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 ($ae_loc.account_id) {
    $slct.account_id = $ae_loc.account_id;
	// handle_load_ae_obj_id__account({account_id: $slct.account_id, try_cache: false});
    handle_load_ae_obj_li__sponsorship({account_id: $slct.account_id, try_cache: false});
}

// async function handle_load_ae_obj_id__account({account_id, try_cache=false}) {
//     console.log('*** handle_load_ae_obj_id__account() ***');

//     let params = {};

// 	$ae_loc.hub.account_id_qry_status = 'loading';
//     ae_account_obj_get_promise = api.get_ae_obj_id_crud({
//         api_cfg: $ae_api,
//         obj_type: 'account',
//         obj_id: account_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 (account_obj_get_result) {
//         if (account_obj_get_result) {
//             $slct.account_obj = account_obj_get_result;
//             console.log(`account object:`, $slct.account_obj);
//         }

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

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

//     return ae_account_obj_get_promise;
// }

async function handle_load_ae_obj_li__sponsorship({account_id, try_cache=true}) {
    console.log('*** handle_load_ae_obj_li__sponsorship() ***');
    // console.log($ae_loc.mod.sponsorships);

    // let fulltext_search_qry_str = ($ae_loc.mod.sponsorships && $ae_loc.mod.sponsorships.fulltext_search_qry_str ? $ae_loc.mod.sponsorships.fulltext_search_qry_str : '');
    // let qry_virtual = $ae_loc.mod.sponsorships.qry_virtual;
    // let qry_physical = $ae_loc.mod.sponsorships.qry_physical;
    // let qry_type = $ae_loc.mod.sponsorships.qry_type;

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

    let params = {};
    // params['example1'] = 'all';
    // params['example2'] = false;

    let params_json: key_val = {};
    // if (fulltext_search_qry_str && fulltext_search_qry_str.length > 2) {
    //     params_json['ft_qry'] = {
    //         'default_qry_str': fulltext_search_qry_str,
    //         'location_address_json': fulltext_search_qry_str,
    //         'contact_li_json': fulltext_search_qry_str,
    //         'address_default_qry_str': fulltext_search_qry_str, // NOTE: Remove after going live with OSIT ae?
    //         'contact_1_default_qry_str': fulltext_search_qry_str, // NOTE: Remove after going live with OSIT ae?
    //         };
    // }

    // if (qry_virtual || qry_physical || qry_type) {
    //     params_json['and_qry'] = {};
    //     if (qry_virtual) params_json['and_qry']['virtual'] = true;
    //     if (qry_physical) params_json['and_qry']['physical'] = true;
    //     if (qry_type) params_json['and_qry']['type'] = qry_type;
    // }

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

    // NOTE: I am not sure if this is actually needed. It may save a little space in the URL.
    // if (JSON.stringify(params_json) == JSON.stringify({})) {
    //     params_json = null;
    // }
    $ae_loc.mod.sponsorships.qry_status = 'loading';
    ae_sponsorship_obj_li_get_promise = api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship',
        for_obj_type: 'account',
        for_obj_id: account_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 (sponsorship_obj_li_get_result) {
        if (sponsorship_obj_li_get_result) {
            $slct.sponsorship_obj_li = sponsorship_obj_li_get_result;
        } else {
            $slct.sponsorship_obj_li = [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        $ae_loc.mod.sponsorships.qry_status = 'done';
        // console.log('Sponsorship list:', $slct.sponsorship_obj_li);
    });

    return ae_sponsorship_obj_li_get_promise;
}


// Load the Sponsorship Cfg Obj with ID based on the URL param.
if (data.url.searchParams.get('sponsorship_cfg_id')) {
    $slct.sponsorship_cfg_id = data.url.searchParams.get('sponsorship_cfg_id');
    $slct_trigger = 'load__sponsorship_cfg_obj';
} else {
    $slct.sponsorship_cfg_id = $ae_loc.mod.sponsorships.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: 1
        })
    .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.
$: if ($slct_trigger == 'load__sponsorship_obj' && $slct.sponsorship_id) {
    console.log('Selected Sponsorship ID:', $slct.sponsorship_id);

    $slct_trigger = null;

    // $ae_loc.mod.sponsorships.link = `${$ae_loc.href_url}/id/${$slct.sponsorship_id}`;

    // $ae_loc.mod.sponsorships.link = `${data.url.origin}/sponsorships/${$slct.sponsorship_id}`;
    // console.log('Sponsorship link:', $ae_loc.mod.sponsorships.link);
    // $ae_loc = $ae_loc;

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

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, "*");

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

    return ae_sponsorship_obj_get_promise;
}


// const modal_view__sponsorship_obj: ModalSettings = {
// 	type: 'component',
// 	component: 'modal_component_view__sponsorship_obj',
// };

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

//     $slct_trigger = null;
// }



// const modal: ModalSettings = {
// 	type: 'alert',
// 	// Data
// 	title: 'Example Alert',
// 	body: 'This is an example modal.',
// 	image: 'https://i.imgur.com/WOgTG96.gif',
// };
// modalStore.trigger(modal);


// const drawerStore = getDrawerStore();

// const drawer_settings_edit: DrawerSettings = {
// 	id: 'sponsorships__edit',
// 	meta: { foo: 'bar', fizz: 'buzz', age: 40 }
// };

// const drawer_settings_x: DrawerSettings = {
// 	id: 'example-1',
// 	meta: { foo: 'bar', fizz: 'buzz', age: 40 }
// };

// const drawer_settings_y: DrawerSettings = {
// 	id: 'example-2',
// 	// Provide your property overrides:
// 	bgDrawer: 'bg-purple-900 text-white',
// 	bgBackdrop: 'bg-gradient-to-tr from-indigo-500/50 via-purple-500/50 to-pink-500/50',
// 	width: 'w-[280px] md:w-[480px]',
// 	padding: 'p-4',
// 	rounded: 'rounded-xl',
// };

</script>


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

        <h1 class="h1 text-center">&AElig; - Sponsorships</h1>
        <section>
            <button
                class="btn variant-ghost-primary"
                on:click={() => {
                    // $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
                    $slct.sponsorship_id = null;
                    $slct.sponsorship_obj = null;

                    // modalStore.trigger(modal_edit__sponsorship_obj);
                    $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
                    $slct_trigger = 'show_edit__sponsorship_obj';
                }}
                >
                <span class="fas fa-edit mx-1"></span>
                Start/Edit Sponsorship
            </button>

            <!-- <button
                on:click={() => {
                    console.log('Open drawer');
                    drawerStore.open(drawer_settings_x);
                }}
                >
                Open Drawer X
            </button> -->

            <!-- <button
                on:click={() => {
                    console.log('Open drawer');
                    drawerStore.open(drawer_settings_y);
                }}
                >
                Open Drawer Y
            </button> -->

            <!-- <button
                on:click={() => {
                    console.log('Open drawer');
                    drawerStore.open(drawer_settings_edit);
                }}
                >
                Open Drawer Edit
            </button> -->
        </section>

		<section class="sponsorships_list">
            {#await ae_sponsorship_obj_li_get_promise}
            <div class="modal-loading">
                <span class="fas fa-spinner fa-spin"></span>
                <span class="loading-text">
                    Loading...
                </span>
            </div>
            {/await}
        {#if $slct.sponsorship_obj_li && $ae_loc.mod.sponsorships.show_list__sponsorship_obj_li}
        <!-- <p>Got a list!</p> -->
        <List_sponsorship_obj />
        {/if}
        </section>

        <!-- <section class="sponsorships_editing">
        {#if $slct.sponsorship_obj && $ae_loc.mod.sponsorships.show_edit__sponsorship_obj}
            <p>Edit!</p>
            <Edit_sponsorship_obj />
        {/if}
        </section> -->

        <!-- <section class="sponsorships_viewing">
        {#if $slct.sponsorship_obj && $ae_loc.mod.sponsorships.show_view__sponsorship_obj}
            <p>Viewing!</p>
            <View_sponsorship_obj />
        {/if}
        </section> -->

	</div>
</div>


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