<script>
    import { createEventDispatcher, getContext } from "svelte";
    import Icon from "../common/Icon.svelte";
    import FileIndex from "./FileIndex.svelte";
    import Dropdown from "../common/Dropdown.svelte";

    let dialogEl;
    export let presetMode = false;

    const dispatch = createEventDispatcher();
    const channel = getContext("channel");
    $: files = [];
    $: selectedFiles = [];
    // onMount(() => {
    //     load();
    // });

    export function close(e) {
        if (e) {
            e.preventDefault();
        }

        dialogEl.close();
        selectedFiles = [];
    }

    function load(recordId) {
        fetch(channel.lucentUrl + "/records/files/?recordId=" + recordId)
            .then((response) => response.json())
            .then((json) => {
                files = json;
            })
            .catch((error) => console.log(error));
    }

    function insert(e, preset) {
        e.preventDefault();
        dispatch("insert_files", { files: selectedFiles, preset: preset });
    }

    function replace(e) {
        e.preventDefault();
        dispatch("replace_files", selectedFiles);
    }

    export function open(recordId) {
        dialogEl.showModal();
        load(recordId);
    }
</script>

<dialog bind:this={dialogEl}>
    <div class="dialog-header">
        {#if presetMode}
            <Dropdown>
                <div slot="button">Insert Preset</div>
                {#each channel.imagePresets as preset}
                    <button
                        class=" dropdown-item button"
                        on:click={(e) => insert(e, preset)}
                        >{preset.name}</button
                    >
                {/each}
            </Dropdown>
        {:else}
            <button
                type="button"
                class="button"
                on:click={insert}
                disabled={selectedFiles.length === 0}
            >
                Insert
            </button>
            <button
                type="button"
                class="button"
                on:click={replace}
                disabled={selectedFiles.length === 0}
            >
                Replace
            </button>
        {/if}
        {#if selectedFiles.length > 0}
            <span class="">
                {selectedFiles.length} records selected
            </span>
        {/if}

        <button
            on:click|preventDefault={close}
            type="button"
            class="button close"
            aria-label="Close"
        >
            <Icon icon="close"></Icon>
        </button>
    </div>

    <div class="dialog-body">
        <FileIndex {files} bind:selected={selectedFiles}></FileIndex>
    </div>
</dialog>
