<script lang="ts">
console.log(`ae_events_pres_mgmt session [slug] form_agree.svelte`);

export let data: any;

import { onMount } from 'svelte';
import { clipboard, FileDropzone } from '@skeletonlabs/skeleton';
import { liveQuery } from "dexie";

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import Element_data_store from '$lib/element_data_store.svelte';
import Element_ae_crud from '$lib/element_ae_crud.svelte';

import { ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { db_events } from "$lib/db_events";
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';


let ae_triggers: key_val = {};
let ae_promises: key_val = {}; // Promise<any>;
let ae_placeholder_li: key_val = {};

let lq__event_session_obj = liveQuery(
    () => db_events.sessions.get($events_slct.event_session_id)
);

// let lq__event_presentation_obj = liveQuery(
//     async () => await db_events.presentations.get($events_slct.event_presentation_id)
// );

console.log(`$events_slct.event_presenter_id:`, $events_slct.event_presenter_id);
let lq__event_presenter_obj = liveQuery(
    () => db_events.presenters.get($events_slct.event_presenter_id)
);

let lq__event_file_obj_li = liveQuery(
    () => db_events.files.where('event_presenter_id_random').equals($events_slct.event_presenter_id).toArray()
);

// $events_slct.event_presenter_obj = $lq__event_presenter_obj;

// $events_sess.pres_mgmt.disable_submit__opt_out = false;

// let tmp_agree = false;
// let tmp_opt_out: key_val = {
//     audio: false,
//     video: false,
//     transcription_and_publication: false,
//     publication_in_app: false
// };

onMount(() => {
    console.log('Events Session [slug]: presenter_view.svelte');
    console.log(`$events_slct.event_presenter_id:`, $events_slct.event_presenter_id);
    console.log(`$lq__event_presenter_obj:`, $lq__event_presenter_obj);
});


// async function handle_submit_form(event) {
//     console.log('*** handle_submit_form() ***');

//     $events_sess.pres_mgmt.disable_submit__opt_out = true;
//     $events_sess.pres_mgmt.submit_status = 'saving';

//     // Data in
//     let form_data = new FormData(event.target);
//     console.log(form_data);

//     let opt_out_di: key_val = ae_util.extract_prefixed_form_data({prefix: null, form_data: form_data, trim_values: true, bool_tf_str: true, log_lvl: 0});
//     console.log(`opt_out_di:`, opt_out_di);

//     // Data out
//     let opt_out_do: key_val = {};
//     opt_out_do.optout_audio = opt_out_di.optout_audio??false;
//     opt_out_do.optout_video = opt_out_di.optout_video??false;
//     opt_out_do.optout_transcription_and_publication = opt_out_di.optout_transcription_and_publication??false;
//     opt_out_do.optout_publication_in_app = opt_out_di.optout_publication_in_app??false;

//     console.log(`opt_out_do:`, opt_out_do);

//     let data_out = {
//         data_json: opt_out_do,
//     }

//     ae_promises.update__event_presenter_obj = await handle_update__event_presenter({
//         obj_type: 'event_presenter',
//         obj_id: $lq__event_presenter_obj?.event_presenter_id_random,
//         data: data_out
//     });
//     console.log(ae_promises.update__event_presenter_obj);

//     $events_sess.pres_mgmt.disable_submit__opt_out = false;
//     $events_sess.pres_mgmt.submit_status = 'saved';
// }


// async function handle_update__event_presenter({
//     obj_type,
//     obj_id,
//     data
//     }) {
//     console.log('*** handle_update__event_presenter() ***');

//     ae_promises.update__event_presenter_obj = api.update_ae_obj_id_crud({
//         api_cfg: $ae_api,
//         obj_type: obj_type,
//         obj_id: obj_id,
//         fields: data,
//         key: $ae_api.api_crud_super_key,
//         return_obj: true,
//         log_lvl: 2
//         })
//     .then(async function (update__obj_result) {
//         if (!update__obj_result) {
//             console.log('The result was null or false.');
//             return false;
//         } else {
//             console.log(`update__obj_result = `, update__obj_result);
//         }
//         $slct_trigger = 'load__event_presenter_obj_li';
//         return update__obj_result;
//     })
//     .catch(function (error) {
//         console.log('Something went wrong.');
//         console.log(error);
//         return false;
//     });

//     return ae_promises.update__event_presenter_obj;
// }


async function handle_submit_form_files(event) {
    console.log('*** handle_submit_form() ***');

    $events_sess.pres_mgmt.disable_submit__event_file_obj = true;
    $events_sess.pres_mgmt.submit_status = 'saving';

    let hosted_file_results;

    if (event.target.presenter_event_file.files.length > 0) {

        hosted_file_results = await handle_input_upload_files(event.target.presenter_event_file.files);


        if (hosted_file_results) {
            console.log(`hosted_file_results:`, hosted_file_results);
        } else {
            console.log(`hosted_file_results:`, hosted_file_results);
        }
    }

    $events_sess.pres_mgmt.disable_submit__event_file_obj = false;
}


async function handle_input_upload_files(input_upload_files) {
    console.log('*** handle_input_upload_files() ***');

    let link_to_type = 'event_presenter';
    let link_to_id = $events_slct.event_presenter_id;

    const form_data = new FormData();

    form_data.append('account_id', $ae_loc.account_id);
    form_data.append('link_to_type', link_to_type);
    form_data.append('link_to_id', link_to_id);

    for (let i = 0; i < input_upload_files.length; i++) {
        form_data.append(`file_list`, input_upload_files[i]);
    }

    let params = null;

    let endpoint = '/hosted_file/upload_files';

    console.log(form_data);

    params = null;

    // Uncomment and the post_promise is not seen by the "await" below
    // post_promise = await api.post_object({api_cfg: $cfg.api, endpoint: endpoint, params: params, data:form_data});
    // Uncomment so that the post_promise is not seen by the "await" below
    ae_promises.upload__hosted_file_obj = await api.post_object({api_cfg: $ae_api, endpoint: endpoint, params: params, form_data: form_data})

    .then(async function (result) {
        // NOTE: The /hosted_file/upload_files endpoint will always return a list of successful files uploaded. In this case we are only uploading one file and expecting a list of one item.
        let x = 0;
        console.log(result[x]);
        let hosted_file_obj = result[x];

        let hosted_file_id = hosted_file_obj.hosted_file_id_random;

        let event_file_data: key_val = {};
        event_file_data['hosted_file_id_random'] = hosted_file_id;
        event_file_data['for_type'] = link_to_type;
        event_file_data['for_id_random'] = link_to_id;
        event_file_data['filename'] = hosted_file_obj.filename;
        event_file_data['extension'] = hosted_file_obj.extension;
        event_file_data['enable'] = true;
        console.log(event_file_data);

        // $events_sess.pres_mgmt.new_upload_list[i].uploaded_bytes = 10; // fake 10 bytes at least...

        let event_file_id = await events_func.create_event_file_obj_from_hosted_file_async({
            api_cfg: $ae_api,
            hosted_file_id: hosted_file_id,
            data: event_file_data,
            log_lvl: 2
            })
        .then(function (create_result) {
            console.log(create_result); // NOTE: This should be the event_file_id string
            // let event_file_id = create_result;
            return create_result;
        });

        return event_file_id;
    })
    .then(function (event_file_id) {
        // NOTE: Need to make sure the event file records are created first. The update won't see the changes if too fast.
        // dispatch(
        //     'event_file_obj_li_updated',
        //     {
        //         link_to_type: link_to_type,
        //         link_to_id: link_to_id,
        //     }
        // );

        // $ae_events.pres_mgmt.new_upload_list[i].uploaded = true;
        // $ae_events.pres_mgmt.new_upload_list[i].uploaded_bytes = event.target.event_file_upload_file_list.files[i].size;

        return event_file_id;
    })
    .catch(function (error) {
        console.log('Something went wrong.');
        console.log(error);
        return false;
    })
    .finally(function (event_file_id) {
        // $events_sess.pres_mgmt.files_uploading_count--;
        return event_file_id;
    });





    console.log(ae_promises.upload__hosted_file_obj);
    let hosted_file_result = ae_promises.upload__hosted_file_obj;

    return hosted_file_result;
}

</script>

{#await $lq__event_presenter_obj}
    Loading...
{:then result}

{#if $lq__event_presenter_obj}
<h2 class="h3">
    Presenter Details for:<br>
    <strong>{$events_slct.presenter_obj.full_name} ({$events_slct.presenter_obj.email})</strong>
</h2>

<section class="p-2">
<h3 class="h4">Title: "{$events_slct.presentation_obj.name}"</h3>
<h3 class="h4">Presenter:</h3>
<ul
    class="space-y-2 px-4"
    >
    <li>
        <span class="fas fa-user"></span>
        {$events_slct.presenter_obj.full_name}
    </li>
    <li>
        <span class="fas fa-envelope"></span>
        <a
            href="mailto:{$events_slct.presenter_obj.email}"
            class="text-blue-500"
            >{$events_slct.presenter_obj.email}</a>
    </li>
    <!-- <li>
        <span class="fas fa-phone"></span>
        {$events_slct.presenter_obj.phone}
    </li> -->
    <li>
        <span class="fas fa-building"></span>
        {$events_slct.presenter_obj.affiliations}
    </li>
    <li>
        <span class="fas fa-user-tag"></span>
        {$events_slct.presenter_obj.professional_title ?? '-- not set --'}
    </li>
    <li>
        <span class="fas fa-user-secret"></span>
        {$events_slct.presenter_obj.person_passcode} (your passcode)

        <button title="Edit your passcode" class="btn btn-sm  variant-soft-warning">
            <span class="fas fa-edit">
            </span>
            Edit
        </button>
    </li>
    <li>
        {#if $ae_loc.trusted_access}
        <!-- A button to copy the access link to the clipboard. -->
        <!-- Example: /events_pres_mgmt/session/Wh8UnJlbIA0?person_id=fV1dl_IJ0yY&person_pass=abc123 -->
        <button
            type="button"
            class="btn btn-sm variant-soft-warning"

            use:clipboard={encodeURI(`${$ae_loc.url_origin}/events_pres_mgmt/session/${$events_slct.event_session_id}?person_id=${$events_slct.presenter_obj.person_id_random}&person_pass=${$events_slct.presenter_obj.person_passcode}&presentation_id=${$events_slct.presentation_obj.event_presentation_id_random}&presenter_id=${$events_slct.presenter_obj.event_presenter_id_random}`)}
            >
            <span class="fas fa-copy mx-1"></span>
            Copy Access Link
        </button>
        {/if}
    </li>
</ul>

<h3 class="h4">Files: {$events_slct.presenter_obj.file_count ? `${$events_slct.presenter_obj.file_count}x` : '-- none --'}</h3>

<span class="text-muted bg-orange-100 p-2 rounded-md text-center">
WARNING: This is a work in progress. The file upload feature is not yet fully functional.
</span>
<form
    class="modal-form {$ae_loc.hub.classes__form}"
    on:submit|preventDefault={handle_submit_form_files}
    >

<label for="input__presenter_event_file">
    Upload outline or draft file(s):
    <FileDropzone
        id="input__presenter_event_file"
        name="presenter_event_file"
        padding="p-1"
        accept="*"
        class="w-96 variant-glass-warning"
        on:change={(e) => {
            console.log('*** FileDropzone change event ***', e);

            if (e.target.files.length) {
                ae_placeholder_li.new_file = `Ready to upload: ${e.target.files[0].name}`;
            } else {
                ae_placeholder_li.new_file = null;
            }
        }}
        >
        <svelte:fragment slot="lead"><span class="fas fa-file-upload"></svelte:fragment>
        <svelte:fragment slot="message"><strong>Upload your file</strong> (drag and drop)</svelte:fragment>
        <svelte:fragment slot="meta">Presentation related files only<br>(PowerPoint, Keynote, PDF, mp4, Word Doc, Excel, txt, etc)</svelte:fragment>

        {ae_placeholder_li.new_file ?? 'No files selected.'}
    </FileDropzone>
</label>

<button
    type="submit"
    class="btn btn-md variant-ghost-secondary m-2"
    disabled={($events_sess.pres_mgmt.disable_submit__event_file_obj)}
    on:click={() => {
        console.log('*** Save button clicked ***');
        // if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}
        // handle_submit_form();
        // handle_submit_form;
    }}
    >
    <span class="fas fa-save mx-1"></span>
    Upload File
</button>

</form>


{#if $lq__event_file_obj_li}
    <ul
        class="space-y-2 px-4"
        >
        {#each $lq__event_file_obj_li as event_file_obj}
            <li>
                <!-- <span class="fas fa-file"></span> -->
                <!-- <a
                    href={file_obj.url}
                    class="text-blue-500"
                    >{file_obj.filename}</a> -->

                <button
                    class="btn btn-md variant-soft-primary"
                    on:click={() => {
                        // ae_promises[event_file_obj.event_file_id_random]
                        ae_promises[event_file_obj.event_file_id_random] = api.download_hosted_file({
                            api_cfg: $ae_api,
                            hosted_file_id: event_file_obj.hosted_file_id_random,
                            return_file: true,
                            filename: event_file_obj.filename,
                            auto_download: true,
                            log_lvl: 1
                        });

                        // window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj.event_file_id_random, filename: event_file_obj.filename, auto_download: true }, '*');
                    }}
                    title={`Download this file: ${event_file_obj.filename} [API] -- SHA256 hash: ${event_file_obj.hash_sha256.slice(0, 10)}...`}
                    >
                    {#await ae_promises[event_file_obj.event_file_id_random]}

                        <span class="mx-1">
                            <span class="fas fa-spinner fa-spin mx-1"></span>

                            Downloading

                            {#if $ae_sess.download[`/hosted_file/${event_file_obj.hosted_file_id_random}/download`]}
                                {$ae_sess.download[`/hosted_file/${event_file_obj.hosted_file_id_random}/download`].percent_completed}%
                            {/if}
                            :
                        </span>
                    {:then}
                        <span class="fas fa-download mx-1"></span>
                        Download:
                    {/await}

                    {event_file_obj.filename.slice(0, 20)}...{event_file_obj.extension}
                </button>
            </li>
        {/each}
    </ul>
{:else}
    <p>No files uploaded</p>
{/if}



<!-- <ul
    class="space-y-2 px-4"
    >
    {#if $events_slct.presenter_obj.file_li}
        {#each $events_slct.presenter_obj.file_li as file_obj}
            <li>
                <span class="fas fa-file"></span>
                <a
                    href={file_obj.url}
                    class="text-blue-500"
                    >{file_obj.name}</a>
            </li>
        {/each}
    {:else}
        <li>
            <span class="fas fa-file"></span>
            No files uploaded
        </li>
    {/if}
</ul> -->

</section>

{/if}

{/await}
