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

    let dialogEl;

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

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

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

    function load(schema) {
        axios
            .get(channel.lucentUrl + "/content/" + schema)
            .then((response) => {
                data = response.data;
            })
            .catch((error) => console.log(error));
    }

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

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

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

<dialog bind:this={dialogEl}>
    {#if data.schema}
        <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">
            <Index {...data} bind:selected={selectedRecords}></Index>
        </div>
    {/if}
</dialog>
