<template>
    <div>
        <table v-if="events.length > 1" class="event-table">
            <tr v-for="event in events" :key="event.id">
                <td>
                    <div v-if="hasImage(event)" class="event-image"><img v-if="imageMap[event.relatedImage]"
                            :src="imageMap[event.relatedImage]" /></div>
                    <div v-if="shouldDisplay('name')" class="event-name">{{ event.name }}</div>
                    <div>{{ formatDateOrDay(event.date, event.dayOfWeek) }}</div>
                    <div v-if="shouldDisplay('time')">{{ formatTime(event.time) }} <span v-if="event.endTime"> - {{
                            formatTime(event.endTime) }}</span> Uhr</div>
                    <div v-if="shouldDisplay('place')">{{ event.eventPlace?.name }}</div>
                    <div v-if="shouldDisplay('description')" class="description">{{ event.description }}</div>
                    <div v-if="shouldDisplay('contactPerson')">{{event.contactPersons.map(cp => formatContactPerson(cp)).join(', ')}}
                    </div>
                    <div v-if="shouldDisplay('institution')">{{ event.institution?.name }}</div>
                    <div v-if="shouldDisplay('type')">{{ event.eventType?.caption }}</div>
                </td>
            </tr>
        </table> 
        <div v-else-if="events.length === 1"
            :class="events[0].alsoOnHomepage && config.id === 'home' ? 'homepage' : ''">
            <div v-if="hasImage(events[0])" class="event-image"><img v-if="imageMap[events[0].relatedImage]"
                    :src="imageMap[events[0].relatedImage]" /></div>
            <div v-if="shouldDisplay('name')" class="event-name">{{ events[0].name }}</div>
            <div>{{ formatDateOrDay(events[0].date, events[0].dayOfWeek) }}</div>
            <div v-if="shouldDisplay('time')">{{ formatTime(events[0].time) }} <span v-if="events[0].endTime"> - {{
                formatTime(events[0].endTime) }}</span> Uhr</div>
            <div v-if="shouldDisplay('place')">{{ events[0].eventPlace?.name }}</div>
            <div v-if="shouldDisplay('description')" class="description">{{ events[0].description }}</div>
            <div v-if="shouldDisplay('contactPerson')">{{events[0].contactPersons.map(cp => formatContactPerson(cp)).join(', ')}}
            </div>
            <div v-if="shouldDisplay('institution')">{{ events[0].institution?.name }}</div>
            <div v-if="shouldDisplay('type')">{{ events[0].eventType?.caption }}</div>
        </div>
    </div>
</template>

<script>
import axios from '@/axios';
import { format } from 'date-fns';
import { formatTime } from '@/utils/strings';

export default {
    name: 'EventRender',
    props: {
        config: {
            type: Object,
            required: true,
        }
    },
    data() {
        return {
            events: [],
            imageMap: {},
        };
    },
    async created() {
        await this.fetchEvents();
    },
    methods: {
        formatTime,
        async fetchEvents() {
            try {
                const response = await axios.post('/events/filter',
                    this.config
                );
                this.events = response.data.events;
                await Promise.all(
                    this.events
                        .filter(event => this.hasImage(event))
                        .map(async event => {
                            try {
                                const response = await axios.get('/image/' + event.relatedImage);
                                this.imageMap[event.relatedImage] = '/images/uploads/' + response.data.filename;
                            } catch (err) {
                                console.error(`Bild konnte nicht geladen werden (ID ${event.relatedImage}):`, err);
                            }
                        })
                );
            } catch (error) {
                console.error('Fehler beim Abrufen der Events', error);
            }
        },
        shouldDisplay(field) {
            return this.config.display.includes(field);
        },
        formatDateOrDay(date, dayOfWeek) {
            if (date) {
                return format(new Date(date), 'dd.MM.yyyy');
            } else if (dayOfWeek !== null && dayOfWeek !== undefined) {
                const daysOfWeek = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
                return daysOfWeek[dayOfWeek];
            }
            return '';
        },
        hasImage(event) {
            return event.relatedImage && event.relatedImage != '';
        },
        async imagePath(eventImage) {
            const response = await axios.get('/image/' + eventImage);
            const path = '/images/uploads/' + response.data.filename;
            console.log(path);
            return path;
        },
        formatContactPerson(contactPerson) {
            if (!contactPerson.expiryDate) {
                return contactPerson.name;
            }
            const date = new Date(contactPerson.expiryDate);
            const formattedDate = date.toLocaleDateString('de-DE', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
            });
            return `${contactPerson.name} (bis ${formattedDate})`;
        }
    }
};
</script>

<style scoped>
.event-name {
    font-weight: bold;
}

.event-table {
    border-collapse: collapse;
}

.event-table td {
    border: 1px solid black;
}

.homepage {
    border: 1px solid #9400ff;
    padding: 0.5em;
    text-align: center;
}

.description {
    padding: 0.5em 0;
}

.event-image > img {
    max-width: 12em;
    max-height: 12em;
}
</style>
