<script>
    import { createEventDispatcher, getContext } from "svelte";

    const dispatch = createEventDispatcher();

    const channel = getContext("channel");
    export let recordId;
    let mimeTypes = "";
    let files = [];
    let isLoading = false;
    // export function onUploadComplete(files){
    //     console.log(files)
    // }

    function upload(e) {
        isLoading = true;
        files = e.target.files ? [...e.target.files] : [];
        let formData = new FormData();

        formData.append("recordId", recordId);
        Array.from(files).forEach(function (file) {
            formData.append("files[]", file);
        });
        dispatch("beforeUpload", files);
        fetch(channel.lucentUrl + "/files/upload", {
            method: "POST",
            body: formData,
            headers: {
                "X-CSRF-TOKEN": document.querySelector(
                    'meta[name="csrf-token"]',
                ).content,
            },
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.error) {
                    dispatch("uploadError", data.error);
                } else {
                    dispatch("uploadComplete", data);
                }
                isLoading = false;
            })
            .catch((error) => {
                isLoading = false;
                console.log(error);
            });
    }
</script>

<fieldset class="upload-button" disabled={isLoading}>
    <label class="button primary btn-spinner">
        <span
            class="spinner-border spinner-border-sm"
            role="status"
            aria-hidden="true"
        />
        Upload file

        <input
            on:input={upload}
            class="form-control"
            type="file"
            id="formFile"
            multiple
            accept={mimeTypes}
            disabled={isLoading}
            hidden
        />
    </label>
</fieldset>
