<template>
    <span v-if="title" @click="downloadFile">{{ title }}</span>
</template>

<script>
import axios from 'axios';

export default {
    name: 'DownloadLink',
    props: {
        hash: {
            type: String,
            required: true,
        },
    },
    data() {
        return {
            title: '',
            link: '',
        };
    },
    async created() {
        await this.fetchFile();
    },
    methods: {
        async fetchFile() {
            try {
                const response = await axios.get('/files/hash/' + this.hash);
                this.title = response.data.title;
                this.events = response.data.events;
            } catch (error) {
                console.error('Fehler beim Abrufen der Events', error);
            }
        },
        
        async downloadFile() {
            const response = await axios.get(`/files/download/${this.hash}`, {
                responseType: 'blob'
            });
            const blob = new Blob([response.data], { type: response.data.type });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = `${this.title}${this.extension}`;
            link.click();
            window.URL.revokeObjectURL(link.href);

        },
    },
};
</script>

<style scoped>
span {
    cursor: pointer;
    color: blue;
    text-decoration: underline;
}
</style>