<template>
    <div>
        <i class="file outline icon" :class="iconClasses"></i>
        {{ file.name }}
        <progress v-if="percentage > 0" :value="percentage" max="100"></progress>
        <button v-else class="ui mini button" @click="download">Download</button>
        <button class="ui mini button" @click="getPresignedUrl">Url</button>
    </div>
</template>

<script>
    // import { createWriteStream } from 'streamsaver'

    // const jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjMwOGNlZWE1NzI0NTQ0OTNkZTZhMTRlYjMzZGRlMzg1ZWY4NzYyYWJmYmZmYTk1MDBjYTI0MmMzZDNhMDJjNDU3MjgwYTRjMTkwMjYxM2VjIn0.eyJhdWQiOiJnYXRld2F5LWlyZWxhbmQiLCJqdGkiOiIzMDhjZWVhNTcyNDU0NDkzZGU2YTE0ZWIzM2RkZTM4NWVmODc2MmFiZmJmZmE5NTAwY2EyNDJjM2QzYTAyYzQ1NzI4MGE0YzE5MDI2MTNlYyIsImlhdCI6MTUxMjQ3NzU3OCwibmJmIjoxNTEyNDc3NTc4LCJleHAiOjE1MTI3MzY3NzcsInN1YiI6IjYyNyIsInNjb3BlcyI6W119.vWPN8kzq-QlAonyOMAmJTuExAuTZQLxtXZ7W9bjC7VSeJvoUGUBV6mu9eV2FVmvPcuFrbMqee9jGfb64VHIYa6ebQGDNnP0fq3I8SA-0Nlc1HNaE0c4fH-ix2c94i2v_80GyqFACoMyUFzz-WFdT8OSZ62muoUGLZwVpnvcS1wLc7VGvy-O--c7NAGZM_5fAtkZaWETeDrNZ4p1oBgqX3wP0Cd43ykupf25TgxCSQyVItCh8yIWcGDB-JTGT-YSXKEYXU-DCbgYhVm5yNPDw6WkKWlLq_CPAM3_bFJfsyyOQ7Qtp9ds_5bE0uEsoGc0anE8jHQNvsIxQmzNFzOSnOSimAdQJrFd2UTktE6omrZI2bMkyrPt1Qd6MNZhAIkvZM-uD6nS7oEGCLZaFZ5beIDnHAkrGgIqnITW_w65QjrD3ZQekKqonEi95EkrINqvFVUR7hyD7pJ2j0AWkXzuJXnGoxRE0MJfArkgDhIlmsQDpAGkDc5Gft3kjgoGQOrK8RmlVoGBxQVPsOJZjPanvXk15AQzg92oY2F7v2GZMkFR4Y939QDLP4mKm8XEobOny30Iw4U_nIYVEwbCFEhVpC39H57Be3xzqlxTpBwuCoeolzWrcs6X_eHlsED60Al4yUSNwkGfctPBk7Y-bShh7Nc3vHqljYcPb_Gdxki_PoEg'

    /**
     * Preformatted date component
     *
     * @example ./croud-document.md
     */
    export default {
        // name: 'croud-document',

        props: {
            /**
             * Core File object
             */
            file: {
                type: Object,
                required: true,
            },
        },

        data() {
            return {
                percentage: 0,
            }
        },

        computed: {
            iconClasses() {
                const classes = {}
                switch (this.file.mime_type) {
                case ('text/rtf'):
                    classes.file = true
                    break

                case ('application/pdf'):
                    classes.pdf = true
                    classes.red = true
                    break

                case ('application/msword'):
                    classes.word = true
                    classes.blue = true
                    break

                case ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'):
                    classes.excel = true
                    classes.green = true
                    break

                case ('application/powerpoint'):
                    classes.powerpoint = true
                    classes.blue = true
                    break

                default:
                    if (this.file.mime_type.indexOf('image')) {
                        classes.yellow = true
                        classes.image = true
                    }
                }

                return classes
            },
        },

        methods: {
            download() {
                return fetch(`http://files.croudcontrol.dev/download/${this.file.reference}`, {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem('jwt')}`,
                    },
                }).then((res) => {
                    const fileStream = createWriteStream(this.file.name)
                    const writer = fileStream.getWriter()
                    // Later you will be able to just simply do
                    // res.body.pipeTo(fileStream)
                    const resourceSize = res.headers.get('Content-Length')
                    const reader = res.body.getReader()
                    let totalChunkSize = 0

                    const pump = () => reader.read()
                        .then(({ value, done }) => {
                            if (done) return writer.close()

                            totalChunkSize += value.length
                            this.percentage = Math.round((totalChunkSize / resourceSize) * 100)

                            return writer.write(value).then(pump)
                        })

                    // Start the reader
                    pump().then(() => {
                        this.percentage = 0
                        this.controller = null
                    })
                }).catch(console.error)
            },

            getPresignedUrl() {
                return fetch(`http://files.croudcontrol.dev/presign/${this.file.reference}`, {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem('jwt')}`,
                    },
                })
            },
        },
    }
</script>
