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

    let dialogEl;

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

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

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

    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) {
        e.preventDefault();
        dispatch("insert", {
            records: selectedRecords,
            action: "insert",
        });
    }

    function replace(e) {
        e.preventDefault();
        dispatch("insert", {
            records: selectedRecords,
            action: "replace",
        });
    }

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

<dialog bind:this={dialogEl}>
    <div class="dialog-header">
        <button
            type="button"
            class="button"
            on:click={insert}
            disabled={selectedRecords.length === 0}
        >
            Insert
        </button>
        <button
            type="button"
            class="button"
            on:click={replace}
            disabled={selectedRecords.length === 0}
        >
            Replace
        </button>
        {#if selectedRecords.length > 0}
            <span class="">
                {selectedRecords.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={selectedRecords}></FileIndex>
    </div>
</dialog>
