<script>
    import { array_move } from "../../edges/sortEdges";
    import Sortable from "../../libs/Sortable.svelte";
    import PreviewFile from "../previews/PreviewFile.svelte";
    import { getContext } from "svelte";
    import FileDialog from "../../dialog/FileDialog.svelte";
    import Uploader from "../../files/Uploader.svelte";

    const channel = getContext("channel");
    export let field;
    export let record;
    export let value = [];
    let browseModal;

    function removeFile(e) {
        e.preventDefault();
        value = value.filter((f) => !(f.id === e.detail));
    }

    async function reorder(e) {
        value = await array_move(value, e.detail.source, e.detail.target);
    }

    function insertFiles(e) {
        e.preventDefault();
        browseModal.close();
        value = [...(value ?? []), ...(e.detail ?? [])];
    }

    function replaceFiles(e) {
        e.preventDefault();
        browseModal.close();
        value = e.detail ?? [];
    }

    function uploadComplete(e) {
        // value = [...value, e.detail];
    }

    function openBrowseModal(e) {
        e.preventDefault();
        browseModal.open(record.id);
    }
</script>

<div class="mb-0">
    <button class="button" on:click={openBrowseModal}> Browse </button>

    <div>
        <Uploader recordId={record.id} on:uploadComplete={uploadComplete} />
    </div>
</div>
{#if value.length > 0}
    <Sortable sortableClass="mt-3" on:update={reorder}>
        {#each value ?? [] as aFile (aFile.id)}
            <!--This div helps the sorting thing-->
            <div>
                <PreviewFile
                    file={aFile}
                    hasDelete={true}
                    on:remove_file={removeFile}
                ></PreviewFile>
            </div>
        {/each}
    </Sortable>
{/if}
<FileDialog
    bind:this={browseModal}
    on:insert_files={insertFiles}
    on:replace_files={replaceFiles}
></FileDialog>
