<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte';
import { clipboard, FileDropzone } from '@skeletonlabs/skeleton';
import { liveQuery } from "dexie";

const dispatch = createEventDispatcher();

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

import { core_func } from '$lib/ae_core_functions';
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';

export let container_class_li: string|Array<string> = [];
export let link_to_type: string;
export let link_to_id: string;
export let allow_basic: boolean = false;
export let allow_moderator: boolean = false;

export let show_convert_btn: null|boolean = null;

// This more or less overrides the default access control. Some elements may have their own access control.
if ($ae_loc.administrator_access) {
    allow_basic = true;
    allow_moderator = true;
} else if ($ae_loc.trusted_access) {
    allow_basic = true;
    allow_moderator = true;
}

let ae_placeholder_li: key_val = {};
let ae_promises: key_val = {}; // Promise<any>;
let ae_tmp: key_val = {};
ae_tmp.show__file_li = true;
let ae_triggers: key_val = {};

let dq__where_val: string = `${link_to_type}_id_random`;
let dq__where_eq_val: string = link_to_id;

let lq__event_file_obj_li = liveQuery(
    async () => await db_events.files.where(dq__where_val).equals(dq__where_eq_val).toArray()
);

onMount(() => {
    console.log('Element - Manage Event File List');
    console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`);

    $slct_trigger = 'load__event_file_obj_li';
});
</script>


<section class="svelte_component event_file_uploaded_manage {container_class_li}">
<button
    type="button"
    on:click={() => {
        console.log('*** Refresh button clicked ***');
        ae_tmp.show__file_li = false;
        console.log(`$lq__event_file_obj_li:`, $lq__event_file_obj_li);
        $slct_trigger = 'load__event_file_obj_li';
        ae_tmp.show__file_li = true;
    }}
    class="btn btn-sm variant-soft-secondary hover:variant-ghost-warning float-right transition hover:transition-all"
    >
    <span class="fas fa-sync-alt mx-1"></span>
    Refresh Files
</button>

<h3
    class="h6"
    class:hidden={!$lq__event_file_obj_li?.length}
    >
    Manage Files:
    <span class="font-bold bg-success-100 px-4 border rounded-lg border-success-200"
        title="Files for {link_to_type ?? '-- not set --'} {link_to_id ?? '-- not set --'}: {$events_slct.session_obj_li.length ?? 'None'}"
        >
        <span class="fas fa-folder-open mx-1"></span>
        {$lq__event_file_obj_li ? `${$lq__event_file_obj_li.length}x` : '-- none --'}
    </span>
</h3>

{#if $lq__event_file_obj_li && $lq__event_file_obj_li.length}
<div class="overflow-scroll w-full">
<table class="table-auto w-full">
    <thead>
        <tr>
            <th class="text-center">Download File</th>
            <th
                class="text-center"
                class:hidden={!allow_basic}
                >Options</th>
            <th
                class="text-center"
                class:hidden={!allow_basic}
                >Status</th>
            <th class="text-center">Meta</th>
        </tr>
    </thead>

    <tbody>

{#each $lq__event_file_obj_li as event_file_obj}
<tr class="ae_obj obj_event_file border-t border-b border-gray-200 hover:bg-gray-50 hover:border-gray-300">
    <td class="event_file__file align-middle">
        <!-- <div
            class="min-w-full"
            > -->
        <button
            disabled={!allow_basic && !allow_moderator}
            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: 0
                });

                // window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj.event_file_id_random, filename: event_file_obj.filename, auto_download: true }, '*');
            }}
            class="btn btn-sm lg:btn-md variant-soft-primary hover:variant-filled-primary min-w-72 lg:min-w-96"
            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="fas fa-spinner fa-spin mx-1"></span>
                <span class="">
                    Downloading
                    {#if $ae_sess.api_download_kv[event_file_obj.hosted_file_id_random]}
                        {$ae_sess.api_download_kv[event_file_obj.hosted_file_id_random].percent_completed}%
                    {/if}
                    :
                </span>
            {:then}
                <!-- <span class="fas fa-download mx-1"></span> -->
                <span class="fas fa-{ae_util.file_extension_icon(event_file_obj.extension)}"></span>
                <!-- <span class="text-sm">
                Download:
                </span> -->
            {/await}

            <span class="grow">
            {ae_util.shorten_filename({filename: event_file_obj.filename, max_length: 30})}
            </span>

            <span
                class="badge variant-glass-success hover:variant-filled-success text-sm"
                class:hidden={!event_file_obj.file_purpose}
                >
                {event_file_obj.file_purpose}
            </span>

        </button>
        <!-- </div> -->
    </td>
    <td
        class="event_file__options"
        class:hidden={!allow_basic}
        >
        <div class="flex flex-col gap-1 text-sm">
        <button
            disabled={1==1 || !allow_basic}
            class="btn btn-sm variant-glass-tertiary hover:variant-soft-success"
            title="The rename function is not ready yet."
            >
            <span class="fas fa-edit mx-1"></span>
            Rename
        </button>
        <button
            disabled={!allow_basic || !allow_moderator}
            class:hidden={!$ae_loc.administrator_access}
            class="btn btn-sm variant-glass-tertiary hover:variant-soft-success"
            title="Hide this file from the presentation launcher"
            >
            <span class="fas fa-eye mx-1"></span>
            Hide
        </button>
        <button
            disabled={!allow_basic}
            on:click={async () => {
                if (!confirm(`Are you sure you want to delete this file?\n${event_file_obj.filename} [${event_file_obj.event_file_id_random}]`)) {return false;}

                // ae_promises[event_file_obj.event_file_id_random] = handle_delete__event_file({event_file_id: event_file_obj.event_file_id_random});

                ae_promises.delete__event_file_obj = await events_func.handle_delete_ae_obj_id__event_file({
                    api_cfg: $ae_api,
                    event_file_id: event_file_obj.event_file_id_random,
                    log_lvl: 1
                })
            }}
            class="btn btn-sm variant-glass-tertiary hover:variant-soft-success"
            title="Delete this file"
            >
            <span class="fas fa-trash-alt mx-1"></span>
            <!-- <span class="fas fa-minus mx-1"></span> -->
            Delete
        </button>
        </div>
    </td>
    <td
        class="event_file__status"
        class:hidden={!allow_basic}
        >
        <div class="flex flex-col gap-1 items-center text-sm">

        <div class="">
            {#if event_file_obj.open_in_os == 'win'}

                MS Windows <span class="fab fa-windows"></span>

            {:else if event_file_obj.open_in_os == 'mac'}

                Apple macOS <span class="fab fa-apple"></span>

            {/if}
        </div>

        <!-- Select from options for the purpose of this file -->
        <div>
            <label
                for="file_purpose"
                class="text-sm mx-1 hidden"
                >
                Purpose:
            </label>
            <select
                id="file_purpose"
                name="file_purpose"
                disabled={!allow_basic && !allow_moderator}
                value={event_file_obj.file_purpose}
                on:change={e => {
                    // ae_tmp[event_file_obj.event_file_id_random].file_purpose = e.target.value;
                    console.log(`Selected file_purpose: ${e.target.value}`);

                    let event_file_data = {
                        event_file_id_random: event_file_obj.event_file_id_random,
                        file_purpose: e.target.value,
                    };

                    events_func.handle_update_ae_obj__event_file({
                            api_cfg: $ae_api,
                            event_file_id: event_file_obj.event_file_id_random,
                            data_kv: event_file_data,
                            log_lvl: 1
                    })
                    .then (function (update_results) {
                        console.log(`Update results:`, update_results);
                        $slct_trigger = 'load__event_file_obj_li';
                    });



                    // ae_triggers.update_event_file_purpose = true;
                }}
                class="select min-w-fit max-w-fit text-sm mx-1 border border-gray-300 rounded-md p-1 hover:border-gray-400"
                >
                <option value={null} selected={!event_file_obj.file_purpose} class="text-xs">-- purpose not set --</option>
                <option value="outline" selected={event_file_obj.file_purpose === 'outline'}>1. Outline</option>
                <option value="draft" selected={event_file_obj.file_purpose === 'draft'}>2. Draft</option>
                <option value="final" selected={event_file_obj.file_purpose === 'final'}>3. Final</option>
                <!-- <option value="supporting">X. Supporting File (audio, video, data, etc)</option> -->
                <!-- <option value="handout">X. Handout</option> -->
                <option value="other">X. Other</option>
                <!-- <option value="poster">Final - Poster</option> -->
                <!-- <option value="presentation">Final - Presentation</option> -->
                <!-- Shows in session room -->
            </select>
        </div>

        </div>

    </td>
    <td class="event_file_info file_meta text-gray-500">
        <div class="flex flex-col text-xs lg:text-sm">
        <!-- {event_file_obj.hosted_file_content_type} -->

        <span class="w-full flex flex-col lg:flex-row justify-between">
        <span>
            Type:
            <strong>{event_file_obj.extension} <span class="fas fa-{ae_util.file_extension_icon(event_file_obj.extension)}"></span>
            </strong>
            <!-- {#if event_file_obj.open_in_os == 'win'}
                <strong>
                MS Windows <span class="fab fa-windows"></span>
                </strong>
            {:else if event_file_obj.open_in_os == 'mac'}
                <strong>
                Apple macOS <span class="fab fa-apple"></span>
                </strong>
            {/if} -->
        </span>
        <span>
            Size:
            <strong>{ae_util.format_bytes(event_file_obj.file_size)}</strong>
        </span>
        </span>

        <span class="w-full flex flex-col lg:flex-row justify-between">
        <span title="SHA 256: {event_file_obj.hash_sha256}">
            Hash: <strong>{event_file_obj.hash_sha256.slice(0, 10)}&mldr;</strong>
        </span>
        <span class:hidden={!$ae_loc.administrator_access}>
            ID:
            <strong>{event_file_obj.hosted_file_id_random}</strong>
        </span>
        </span>

        <span>
            <!-- <span class="fas fa-cloud-upload-alt mx-1"></span> -->
            <!-- Uploaded: -->
            <!-- <span class="fas fa-calendar-day mx-1"></span> -->
             <span class="fas fa-clock mx-1"></span>
            <strong>
            {ae_util.iso_datetime_formatter(event_file_obj.created_on, 'dddd')}
            </strong>
            {ae_util.iso_datetime_formatter(event_file_obj.created_on, 'date_iso')}
            at
            <strong>{ae_util.iso_datetime_formatter(event_file_obj.created_on, 'time_short_no_leading')}</strong>
            <!-- {event_file_obj.updated_on} -->
        </span>

        </div>
    </td>
</tr>
{/each}

    </tbody>
</table>
</div>

{:else}

<p class="text-center text-muted">
    No files uploaded yet.
</p>

{/if}

</section>


<style>

</style>