<script lang="ts">
type key_val = {
    [key: string]: any;
};
// *** Import Svelte core
import { onMount } from 'svelte';

// *** Import Aether core variables and functions
import { ae, api, Element_modal_v3 } from 'aether_npm_lib';

import { slct, slct_trigger, ae_app } from './stores';

// *** Import Aether core components
// import { get_data_store_obj_w_code } from '../data_store/stores_data_store_api.js';

// *** Import Aether module variables and functions
// import { get_account_archive_obj_list } from './stores_ae_api.js';

// *** Import Aether module components
import Edit_archive_obj from './10_edit__archive_obj.svelte';
import List_archive_obj from './10_list__archive_obj.svelte';
import View_archive_obj from './10_view__archive_obj.svelte';

// *** Export/Exposed variables and functions for component
// export let account_id: string = $page['page_for']['account_id'];
export let account_id: string = $ae_app.account_id;
export let archive_id: string = $ae_app.archives.archive_id;

export let novi_uuid: string = $ae_app.novi_uuid;
export let novi_email: string = $ae_app.novi_email;
export let novi_full_name: string = $ae_app.novi_full_name;
export let novi_admin_li: string = $ae_app.novi_admin_li;
export let novi_trusted_li: string = $ae_app.novi_trusted_li;

// *** Set initial variables
$ae_app.novi_uuid = novi_uuid;
$ae_app.novi_email = decodeURIComponent(novi_email);
$ae_app.novi_full_name = decodeURIComponent(novi_full_name);
$ae_app.novi_admin_li = novi_admin_li;
$ae_app.novi_trusted_li = novi_trusted_li;

$ae_app.current_timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (!$ae_app.lu_timezone_list) {
    $ae_app.lu_timezone_list = [];
}

$ae_app.archives.show_main__options = true; // Section for: buttons for creating new archives, show/hide archives, and search archives
// $ae_app.archives.show_list__archive_obj_li = true;
// $ae_app.archives.show_view__archive_obj = $ae_app.archives.show_view__archive_obj;
$ae_app.archives.fulltext_search_qry_str = '';
$ae_app.archives.qry_type = false

// NOTE: Check if the novi_uuid is in the novi_admin_li list
if ($ae_app.novi_uuid && $ae_app.novi_admin_li) {
    if ($ae_app.novi_admin_li.includes($ae_app.novi_uuid)) {
        $ae_app.access_type = 'administrator';
        $ae_app.administrator_access = true;
        $ae_app.trusted_access = true;
    }
}
// NOTE: Check if the novi_uuid is in the novi_trusted_li list
if ($ae_app.novi_uuid && $ae_app.novi_trusted_li) {
    if ($ae_app.novi_trusted_li.includes($ae_app.novi_uuid)) {
        $ae_app.access_type = 'trusted';
        $ae_app.trusted_access = true;
    }
}

if ($ae_app.administrator_access) {
    $ae_app.archives.enabled = 'enabled';
    $ae_app.archives.hidden = 'not_hidden';
    $ae_app.archives.limit = 150;
} else if ($ae_app.trusted_access) {
    $ae_app.archives.enabled = 'enabled';
    $ae_app.archives.hidden = 'not_hidden';
    $ae_app.archives.limit = 75;
} else {
    $ae_app.archives.enabled = 'enabled';
    $ae_app.archives.hidden = 'not_hidden';
    $ae_app.archives.limit = 75;
}

let idaa_archive_obj_li_get_promise;
let idaa_archive_obj_get_promise;

if (account_id) {
    $slct.account_id = account_id;
    handle_load_archive_obj_li({account_id: $slct.account_id, try_cache: false});
}

if (archive_id) {
    console.log(`Selected Archive ID: ${archive_id}`);
    $slct.archive_id = archive_id;
    $slct_trigger = 'load__archive_obj';

    // $ae_app.archives.show_main__options = true;
    $ae_app.archives.show_list__archive_obj_li = false;
    $ae_app.archives.show_view__archive_obj = true;
    $ae_app.archives.show_edit__archive_obj = false;
} else {
    // $ae_app.archives.show_main__options = true;
    $ae_app.archives.show_list__archive_obj_li = true;
    $ae_app.archives.show_view__archive_obj = false;
    $ae_app.archives.show_edit__archive_obj = false;
}

if (!$ae_app.client_content) {
    $ae_app.client_content = {};
}

onMount(() => {
    console.log('** Component Mounted: ** IDAA Archives - AE Archives: Main');
});


$: if ($ae_app.iframe_height && $ae_app.iframe_height_modal_body) {
    console.log('getting new dimensions for iframe:', $ae_app.iframe_height, $ae_app.iframe_height_modal_body);

    let iframe_height = 0;

    if ($ae_app.iframe_height > $ae_app.iframe_height_modal_body) {
        iframe_height = $ae_app.iframe_height;
    } else {
        iframe_height = $ae_app.iframe_height_modal_body;

        // console.log($ae_app.modal_dimensions);

        if ($ae_app.modal_dimensions && $ae_app.modal_dimensions.header_height) {
            iframe_height = iframe_height + $ae_app.modal_dimensions.header_height;
        }
        if ($ae_app.modal_dimensions && $ae_app.modal_dimensions.footer_height) {
            iframe_height = iframe_height + $ae_app.modal_dimensions.footer_height;
        }
        // iframe_height = iframe_height + 50; // Just in case
    }

    console.log(`Suggested new iframe_height: ${iframe_height}`);
    window.parent.postMessage({'iframe_height': iframe_height}, "*"); // This should be in pixels
} else if ($ae_app.iframe_height) {
    console.log('setting new iframe_height:', $ae_app.iframe_height);

    // let iframe_height = $ae_app.iframe_height;

    window.parent.postMessage({'iframe_height': $ae_app.iframe_height}, "*"); // This should be in pixels
}

$: if ($slct_trigger == 'load__archive_obj' && $slct.archive_id) {
    console.log('*** $slct_trigger == load__archive_obj ***');
    $slct_trigger = null;

    handle_load_archive_obj({archive_id: $slct.archive_id, try_cache: false});

    // Auto show the selected Archive ID
    // Is this pushState needed here?
    // Set the URL param "archive_id" to the current Archive ID. This is a just in case.
    // const url = new URL(location);
    // url.searchParams.set('archive_id', $slct.archive_id);
    // history.pushState({}, '', url);

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

    // $ae_app.archives.show_main__options = false;
    // $ae_app.archives.show_list__archive_obj_li = false;
    // $ae_app.archives.show_view__archive_obj = true;
    // $ae_app.archives.show_edit__archive_obj = false;
}

$: if ($slct_trigger == 'load__archive_obj_li' && $slct.account_id) {
    console.log('*** $slct_trigger == load__archive_obj_li ***');
    $slct_trigger = null;

    handle_load_archive_obj_li({account_id: $slct.account_id, try_cache: false});
}

async function handle_load_archive_obj_li({account_id, try_cache=true}) {
    console.log('*** handle_load_archive_obj_li() ***');
    console.log($ae_app.archives);

    let enabled = $ae_app.archives.enabled;
    let hidden = $ae_app.archives.hidden;
    let limit = $ae_app.archives.limit;
    let offset = $ae_app.archives.offset;

    let params = {};

    let params_json: key_val = {};
    if ($ae_app.archives.fulltext_search_qry_str && $ae_app.archives.fulltext_search_qry_str.length > 2) {
        params_json['ft_qry'] = {
            'default_qry_str': $ae_app.archives.fulltext_search_qry_str,
            };
    }

    if ($ae_app.archives.qry_audio || $ae_app.archives.qry_video || $ae_app.archives.qry_other) {
        params_json['and_qry'] = {};
        if ($ae_app.archives.qry_audio) params_json['and_qry']['audio'] = true;
        if ($ae_app.archives.qry_video) params_json['and_qry']['video'] = true;
        if ($ae_app.archives.qry_other) params_json['and_qry']['other'] = $ae_app.archives.qry_other;
    }

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

    idaa_archive_obj_li_get_promise = api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: $ae_app.ae_api,
        obj_type: 'archive', // Archive in this case is an IDAA archive.
        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', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 1
        })

    .then(function (archive_obj_li_get_result) {
        if (archive_obj_li_get_result) {
            $slct.archive_obj_li = archive_obj_li_get_result;
            console.log(`Archive list:`, $slct.archive_obj_li);
        } else {
            $slct.archive_obj_li = [];
        }

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

    return idaa_archive_obj_li_get_promise;
}

async function handle_load_archive_obj({archive_id, try_cache=false}) {
    console.log('*** handle_load_archive_obj() ***');

    // let enabled = $ae_app.archives.enabled;
    // let hidden = $ae_app.archives.hidden;
    // let limit = $ae_app.archives.limit;
    // let offset = $ae_app.archives.offset;

    let params = {};

    idaa_archive_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_app.ae_api,
        obj_type: 'archive',
        obj_id: archive_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 (archive_obj_get_result) {
        if (archive_obj_get_result) {
            $slct.archive_obj = archive_obj_get_result;
            // console.log($slct.archive_obj.cfg_json.content_group_sort);
            $ae_app.archives.content_group_sort = $slct.archive_obj.cfg_json.content_group_sort;
            console.log(`Archive object:`, $slct.archive_obj);
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return idaa_archive_obj_get_promise;
}

function handle_created_archive_obj(event) {
    console.log('*** handle_created_archive_obj() ***');
    console.log(event.detail);

    handle_load_archive_obj({archive_id: $slct.archive_id, try_cache: false});

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

    let message = {'archive_id': $slct.archive_id};
    window.parent.postMessage(message, "*");

    // $slct_trigger = 'load__archive_obj';
    $slct_trigger = 'load__archive_obj_li';

    // $ae_app.archives.show_main__options = false;
    $ae_app.archives.show_list__archive_obj_li = false;
    $ae_app.archives.show_view__archive_obj = true;
    $ae_app.archives.show_edit__archive_obj = false;
}

function handle_updated_archive_obj(event) {
    console.log('*** handle_updated_archive_obj() ***');
    console.log(event.detail);

    $slct_trigger = 'load__archive_obj';
    // NOTE: If the next trigger is set too quickly it will cause the one above to be missed.
    // $slct_trigger = 'load__archive_obj_li';

    // $ae_app.archives.show_main__options = false;
    $ae_app.archives.show_list__archive_obj_li = false;
    $ae_app.archives.show_view__archive_obj = true;
    $ae_app.archives.show_edit__archive_obj = false;
}

function handle_deleted_archive_obj(event) {
    console.log('*** handle_deleted_archive_obj() ***');
    console.log(event.detail);

    const url = new URL(location);
    url.searchParams.delete('archive_id');
    history.pushState({}, '', url);

    let message = {'archive_id': null};
    window.parent.postMessage(message, "*");

    $slct_trigger = 'load__archive_obj_li';

    $ae_app.archives.show_main__options = true;
    $ae_app.archives.show_list__archive_obj_li = true;
    $ae_app.archives.show_view__archive_obj = false;
    $ae_app.archives.show_edit__archive_obj = false;
}
</script>


<section id="osit_idaa_archives" class="osit_archives ae_main c_idaa c_idaa_archives" bind:clientHeight={$ae_app.iframe_height}>
<!-- <header>
    <h1>IDAA Archives</h1>
</header> -->

<section class="ae_section ae_meta">
    <p>
    Novi: {$ae_app.novi_full_name}
    <span class="details">
    (
        {$ae_app.novi_email}
        {#if $ae_app.administrator_access}
            <span class="access_type administrator_access">Administrator</span>
        {:else if $ae_app.trusted_access}
            <span class="access_type trusted_access">Trusted</span>
        {/if}
        <span class="novi_uuid">UUID: {$ae_app.novi_uuid}</span>
    )
    </span>
    </p>
    <!-- <p>Page height: {window.innerHeight}</p> -->
</section>

{#if $ae_app.archives.show_main__options}
<section class="ae_section ae_options ae_column archive_obj__options">

    <!-- <div class="note">A comment about the IDAA archives in general can go here.</div> -->

    <div class="filters_and_search ae_group ae_row">

        <!-- Show/hide hidden content -->

        {#if $ae_app.trusted_access}
            {#if $ae_app.archives.hidden == 'not_hidden'}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'all';
                        $ae_app.archives.limit = 150;
                        $slct_trigger = 'load__archive_obj_li';
                    }}
                    class="btn_new_bb_post ae_btn btn_xs ae_smallest btn btn-xs btn-info"
                    >
                    <span class="fas fa-eye"></span> Show Hidden Archives
                </button>
            {:else}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'not_hidden';
                        $slct_trigger = 'load__archive_obj_li';
                    }}
                    class="btn_new_bb_post ae_btn btn_xs btn btn-xs btn-info"
                    >
                    <span class="fas fa-eye-slash"></span> Hide Hidden Archives
                </button>
            {/if}

            <!-- We only want these options to show if a specific archive is showing. -->
            {#if $ae_app.archives.show_view__archive_obj}
            {#if $ae_app.archives.hidden == 'not_hidden'}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'all';
                        $ae_app.archives.limit = 150;
                        $slct_trigger = 'load__archive_content_obj_li';
                    }}
                    class="btn_new_bb_post ae_btn btn_xs ae_smallest btn btn-xs btn-info"
                    >
                    <span class="fas fa-eye"></span> Show Hidden Content
                </button>
            {:else}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'not_hidden';
                        $slct_trigger = 'load__archive_content_obj_li';
                    }}
                    class="btn_new_bb_post ae_btn btn_xs btn btn-xs btn-info"
                    >
                    <span class="fas fa-eye-slash"></span> Hide Hidden Content
                </button>
            {/if}
            {/if}
        {/if}

        <!-- For administrator access: Show/hide disabled content -->

        {#if $ae_app.administrator_access}
            {#if $ae_app.archives.enabled == 'enabled'}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'all';
                        $ae_app.archives.enabled = 'all';
                        $ae_app.archives.limit = 500;
                        $slct_trigger = 'load__archive_obj_li';
                    }}
                    class="ae_btn btn_xs ae_smallest btn btn-xs btn-warning"
                    >
                    <span class="fas fa-eye"></span> Show Disabled Archives
                </button>
            {:else}
                <button
                    on:click={() => {
                        $ae_app.archives.enabled = 'enabled';
                        $slct_trigger = 'load__archive_obj_li';
                    }}
                    class="ae_btn btn_xs ae_smallest btn btn-xs btn-warning"
                    >
                    <span class="fas fa-eye-slash"></span> Hide Disabled Archives
                </button>
            {/if}

            {#if $ae_app.archives.enabled == 'enabled'}
                <button
                    on:click={() => {
                        $ae_app.archives.hidden = 'all';
                        $ae_app.archives.enabled = 'all';
                        $ae_app.archives.limit = 500;
                        $slct_trigger = 'load__archive_content_obj_li';
                    }}
                    class="ae_btn btn_xs ae_smallest btn btn-xs btn-warning"
                    >
                    <span class="fas fa-eye"></span> Show Disabled Content
                </button>
            {:else}
                <button
                    on:click={() => {
                        $ae_app.archives.enabled = 'enabled';
                        $slct_trigger = 'load__archive_content_obj_li';
                    }}
                    class="ae_btn btn_xs btn btn-xs btn-warning"
                    >
                    <span class="fas fa-eye-slash"></span> Hide Disabled Content
                </button>
            {/if}
        {/if}
    </div>
    <!-- END: div filters_and_search -->

    <div class="view_archvies_create_archive ae_group ae_row">
        {#if $slct.archive_id}
        <button
            on:click={ () => {

                $slct.archive_id = null;
                $slct.archive_obj = {};

                $ae_app.archives.show_main__options = true;
                $ae_app.archives.show_list__archive_obj_li = true;
                $ae_app.archives.show_view__archive_obj = false;
                $ae_app.archives.show_edit__archive_obj = false;
                // $ae_app.iframe_height_modal_body = 0;

                const url = new URL(location);
                url.searchParams.delete('archive_id');
                history.pushState({}, '', url);

                let message = {'archive_id': null};
                window.parent.postMessage(message, "*");
            }}
            class="btn_new_archive ae_btn btn btn-secondary"
            >
            <span class="fas fa-times"></span> View Other Archives
        </button>
        {/if}
        {#if $ae_app.trusted_access}
        <button
            on:click={() => {
                $slct.archive_id = null;
                $slct.archive_obj = {};

                const url = new URL(location);
                url.searchParams.delete('archive_id');
                history.pushState({}, '', url);

                $ae_app.archives.show_main__options = true;
                $ae_app.archives.show_list__archive_obj_li = false;
                $ae_app.archives.show_view__archive_obj = false;
                $ae_app.archives.show_edit__archive_obj = true;
            }}
            class="ae_btn ae_smallest btn_new_archive ae_btn btn btn-warning"
            >
                <span class="fas fa-plus"></span> Create new Archive
        </button>
        {/if}
    </div>

</section>
{/if}


{#if $ae_app.archives.show_list__archive_obj_li}
    <List_archive_obj
        on:created__archive_obj={handle_created_archive_obj}
        on:updated__archive_obj={handle_updated_archive_obj}
        on:deleted__archive_obj={handle_deleted_archive_obj}
        />
{/if}


{#if $ae_app.archives.show_view__archive_obj && $slct.archive_obj}
    <View_archive_obj />
{/if}


</section>


{#if $ae_app.archives.show_edit__archive_obj}
<Element_modal_v3
        show = { true }
        modal_cover_body = { false }
        report_client_dimensions = { true }
        on:close={ () => {
            $ae_app.archives.show_main__options = true;
            $ae_app.archives.show_list__archive_obj_li = true;
            $ae_app.archives.show_edit__archive_obj = false;
            $ae_app.archives.show_view__archive_obj = false;

            const url = new URL(location);
            url.searchParams.delete('archive_id');
            history.pushState({}, '', url);

            let message = {'archive_id': null};
            window.parent.postMessage(message, "*");
        }}
        on:report__modal_dimensions={ (event) => {
            console.log('*** on:report__modal_dimensions ***');
            console.log(event.detail);

            $ae_app.modal_dimensions = event.detail.modal_dimensions;
        }}
        >
    <span slot="header_title">{@html ($slct.archive_obj.name ? $slct.archive_obj.name : 'New Archive Group')}</span>

    <span slot="body">

        <Edit_archive_obj
            on:created__archive_obj={handle_created_archive_obj}
            on:updated__archive_obj={handle_updated_archive_obj}
            on:deleted__archive_obj={handle_deleted_archive_obj}
            />

    </span>
</Element_modal_v3>
{/if}


<!-- {#if $ae_app.archives.show_view__archive_obj && $slct.archive_obj}
<Element_modal_v3
    show = { true }
    modal_cover_body = { true }
    report_modal_dimensions = { true }
    on:close={ () => {

        $slct.archive_id = null;
        $slct.archive_obj = {};

        $ae_app.archives.show_main__options = true;
        $ae_app.archives.show_list__archive_obj_li = true;
        $ae_app.archives.show_view__archive_obj = false;
        $ae_app.archives.show_edit__archive_obj = false;
        $ae_app.iframe_height_modal_body = 0;

        const url = new URL(location);
        url.searchParams.delete('archive_id');
        history.pushState({}, '', url);

        let message = {'archive_id': null};
        window.parent.postMessage(message, "*");
    }}
    on:report__modal_dimensions={ (event) => {
        console.log('*** on:report__modal_dimensions ***');
        console.log(event.detail);

        $ae_app.modal_dimensions = event.detail.modal_dimensions;
    }}
    >
    <span slot="header_title">{@html $slct.archive_obj.name}</span>

    <span slot="body">

        <View_archive_obj />

    </span>
</Element_modal_v3>
{/if} -->


<style>

</style>
