<template>
    <div class="d-inline-block">
        <label for="files">
            <slot></slot>
        </label>
        <input type="file" multiple id="files" @change="loadFiles" class="d-none">
    </div>
</template>

<style scoped>
</style>

<script>
import * as BIcons from "bootstrap-icons-vue";

export default {
    name: "FsFileSource",
    components: {
        ...BIcons
    },
    emits: ["input"],
    methods: {
        loadFiles() {
            const files = document.getElementById("files").files;
            const jobs = [...files].map((file) => {
                return new Promise((resolve, reject) => {
                    var reader = new FileReader();
                    reader.onload = () => {
                        const buffer = reader.result;
                        if (!(buffer instanceof ArrayBuffer)) {
                            console.log(buffer)
                            reject("Not an ArrayBuffer");
                        }
                        const data = new Uint8Array(buffer);
                        const hash = nacl.crypto_hash(data).reduce((a, b) => a + b.toString(16).padStart(2, "0"), "");
                        var base64 = btoa(
                            data.reduce((a, b) => a + String.fromCharCode(b), '')
                        );
                        resolve({
                            name: file.name,
                            size: file.size,
                            mime_type: file.type,
                            data: base64,
                            hash: hash,
                        });
                    };
                    reader.onerror = (e) => {
                        reject(e);
                    };
                    reader.readAsArrayBuffer(file)
                })
            });
            Promise.all(jobs).then((files) => {
                this.$emit("input", files)
            })
        }
    },
}
</script>