<template>
    <div class="d-inline-block" v-if="show_camera">
        <label for="pictures">
            <slot></slot>
        </label>
        <input type="file" accept="image/*" multiple capture="camera" id="pictures" @change="loadFiles" class="d-none">
    </div>
</template>

<style scoped>
</style>

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

export default {
    name: "CameraFileSource",
    components: {
        ...BIcons
    },
    emits: ["input"],
    data() {
        return {
            show_camera: false
        }
    },
    methods: {
        loadFiles() {
            const files = document.getElementById("pictures").files;
            const jobs = [...files].map((file) => {
                return new Promise((resolve, reject) => {
                    var reader = new FileReader();
                    reader.onload = async () => {
                        const buffer = reader.result;
                        if (!(buffer instanceof ArrayBuffer)) {
                            console.log(buffer)
                            reject("Not an ArrayBuffer");
                            return;
                        }
                        const data = new Uint8Array(buffer);
                        // SHA-256 must match the backend's content hash for file identification. See docs/implementation.md#sha-256-file-hashing-must-match-the-backend.
                        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
                        const hash = Array.from(new Uint8Array(hashBuffer))
                            .map(b => b.toString(16).padStart(2, "0")).join("");
                        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)
            })
        }
    },
    mounted() {
        //detect media api
        if ('capture' in document.createElement('input')) {
            console.log('capture supported.');
            this.show_camera = true;
        }

        if (navigator.getUserMedia) {
            console.log('getUserMedia supported.');
            this.show_camera = true;
        }
    }
}
</script>