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

    const dispatch = createEventDispatcher();

    const channel = getContext("channel");
    export let schema;
    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("schema", schema.name);
        Array.from(files).forEach(function (file) {
            formData.append("files[]", file);
        });
        dispatch("beforeUpload", files);
        axios
            .post(channel.lucentUrl + "/files/upload", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            })
            .then((response) => {
                if (response.data.error) {
                    dispatch("uploadError", response.data.error);
                } else {
                    dispatch("uploadComplete", response.data);
                }
                isLoading = false;
            })
            .catch((error) => {
                isLoading = false;
                console.log(error.response.data);
            });
    }
</script>

<fieldset disabled={isLoading}>
    <label class="btn btn-primary btn-sm btn-spinner ">
        Upload file
        <span
            class="spinner-border spinner-border-sm"
            role="status"
            aria-hidden="true"
        >
            <span class="visually-hidden">Loading...</span>
        </span>
        <input
            on:input={upload}
            class="form-control"
            type="file"
            id="formFile"
            multiple
            accept={mimeTypes}
            disabled={isLoading}
            hidden
        />
    </label>
</fieldset>
