<script lang="ts">
    import {Modal} from "flowbite-svelte";
    import {schemRepo} from "../repo/repo.js";
    import {createEventDispatcher} from "svelte";

    const dispatch = createEventDispatcher();

    export let open = false;

    async function upload() {
        if (uploadFile == null) {
            return
        }
        let file = uploadFile[0];

        let name = file.name;

        let type = name.split(".").pop();

        if (type !== "schem" && type !== "schematic") {
            return
        }

        let content = await file.arrayBuffer();

        // @ts-ignore
        let b64 = btoa(String.fromCharCode.apply(null, new Uint8Array(content)));

        await $schemRepo.uploadSchematic(name, b64);

        open = false;
        uploadFile = null;
        dispatch("reset")
    }

    let uploadFile: File[] | null = null;
</script>

<Modal title="Upload Schematic" bind:open autoclose outsideclose>
    <form>
        <input type="file" bind:files={uploadFile} />
    </form>
    <svelte:fragment slot="footer">
        <button class="btn !ml-auto" on:click={upload}>Upload</button>
        <button class="btn btn-gray" on:click={() => open = false}>Close</button>
    </svelte:fragment>
</Modal>