<template>
    <h2>{{ $t('socialnetwork.forum.title') }} {{ forumName }}</h2>
    <div class="creationtoggler">
        <button @click="createNewTopic">{{ $t(!inCreation ? 'socialnetwork.forum.showNewTopic' :
            'socialnetwork.forum.hideNewTopic') }}</button>
    </div>
    <div v-if="inCreation">
        <div>
            <label class="newtitle">
                {{ $t('socialnetwork.forum.topic') }}
                <input type="text" v-model="newTitle" />
            </label>
        </div>
        <editor v-model="newContent" :init="tinymceInitOptions" :api-key="apiKey"
            tinymce-script-src="/tinymce/tinymce.min.js"></editor>
        <button @click="saveNewTopic">{{ $t('socialnetwork.forum.createNewTopic') }}</button>
    </div>
    <div v-else-if="titles.length > 0">
        <div class="pagination">
            <button @click="goToPage(1)" v-if="page != 1">&laquo; {{ $t('socialnetwork.forum.pagination.first')
                }}</button>
            <button @click="goToPage(page - 1)" v-if="page != 1">&lsaquo; {{
                $t('socialnetwork.forum.pagination.previous') }}</button>
            <span>{{ $t('socialnetwork.forum.pagination.page').replace("<<page>>", page).replace("<<of>>", totalPages)
                        }}</span>
            <button @click="goToPage(page + 1)" v-if="page != totalPages">{{ $t('socialnetwork.forum.pagination.next')
                }}
                &rsaquo;</button>
            <button @click="goToPage(totalPages)" v-if="page != totalPages">{{ $t('socialnetwork.forum.pagination.last')
                }}
                &raquo;</button>
        </div>
        <table>
            <thead>
                <tr>
                    <th>{{ $t('socialnetwork.forum.topic') }}</th>
                    <th>{{ $t('socialnetwork.forum.createdBy') }}</th>
                    <th>{{ $t('socialnetwork.forum.createdAt') }}</th>
                    <th>{{ $t('socialnetwork.forum.reactions') }}</th>
                    <th>{{ $t('socialnetwork.forum.lastReaction') }}</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="title in titles">
                    <td><span class="link" @click="openTopic(title.id)">{{ title.title }}</span></td>
                    <td><span class="link" @click="openProfile(title.createdByHash)">{{ title.createdBy }}</span></td>
                    <td>{{ new Date(title.createdAt).toLocaleString() }}</td>
                    <td>{{ title.numberOfItems }}</td>
                    <td>{{ new Date(title.lastMessageDate).toLocaleString() }}</td>
                </tr>
            </tbody>
        </table>
        <div class="pagination">
            <button @click="goToPage(1)" v-if="page != 1">&laquo; {{ $t('socialnetwork.forum.pagination.first')
                }}</button>
            <button @click="goToPage(page - 1)" v-if="page != 1">&lsaquo; {{
                $t('socialnetwork.forum.pagination.previous') }}</button>
            <span>{{ $t('socialnetwork.forum.pagination.page').replace("<<page>>", page).replace("<<of>>", totalPages)
                        }}</span>
            <button @click="goToPage(page + 1)" v-if="page != totalPages">{{ $t('socialnetwork.forum.pagination.next')
                }}
                &rsaquo;</button>
            <button @click="goToPage(totalPages)" v-if="page != totalPages">{{ $t('socialnetwork.forum.pagination.last')
                }}
                &raquo;</button>
        </div>
    </div>
    <div v-else>{{ $t('socialnetwork.forum.noTitles') }}</div>
</template>

<script>
import apiClient from '../../utils/axios';
import TinyMCEEditor from '@tinymce/tinymce-vue';

export default {
    name: 'ForumView',
    components: {
        editor: TinyMCEEditor,
    },
    computed: {
        totalPages() {
            return Math.ceil(this.numberOfItems / 25);
        }
    },
    data() {
        return {
            forumName: 'test',
            forumId: 0,
            page: 1,
            numberOfItems: 0,
            titles: [],
            inCreation: false,
            newTitle: '',
            newContent: '',
            apiKey: import.meta.env.VITE_TINYMCE_API_KEY ?? '',
            tinymceInitOptions: {
                script_url: '/tinymce/tinymce.min.js',
                height: 300,
                menubar: true,
                plugins: [
                    'lists', 'link',
                    'searchreplace', 'visualblocks', 'code',
                    'insertdatetime', 'table'
                ],
                toolbar:
                    'undo redo cut copy paste | bold italic forecolor backcolor fontfamily fontsize| \
                    alignleft aligncenter alignright alignjustify | \
                    bullist numlist outdent indent | removeformat | link visualblocks code',
                contextmenu: 'link image table',
                menubar: 'edit format table',
                promotion: false,
            },
        }
    },
    async mounted() {
        this.forumId = this.$route.params.id;
        await this.loadForum();
    },
    methods: {
        async loadForum() {
            const response = await apiClient.get(`/api/forum/${this.forumId}/${this.page}`);
            this.setData(response.data);
        },
        createNewTopic() {
            this.inCreation = !this.inCreation;
        },
        async saveNewTopic() {
            const response = await apiClient.post('/api/forum/topic', {
                forumId: this.forumId,
                title: this.newTitle,
                content: this.newEntryContent
            });
            this.setData(response.data);
            this.inCreation = false;
        },
        setData(data) {
            this.forumName = data.name;
            this.titles = data.titles;
            this.page = data.page;
            this.numberOfItems = data.totalTopics;
        },
        goToPage(page) {
            if (page >= 1 && page <= this.totalPages) {
                this.page = page;
                this.loadForum();
            }
        },
        openProfile(id) {
            this.$root.$refs.userProfileDialog.userId = id;
            this.$root.$refs.userProfileDialog.open();
        },
        openTopic(topicId) {
            this.$router.push(`/socialnetwork/forumtopic/${topicId}`);
        },
    }
}
</script>

<style lang="scss" scoped>
.creationtoggler {
    margin-bottom: 1em;
}

.newtitle {
    display: flex;
    gap: 1em;
    vertical-align: middle;
}

.newtitle input {
    flex: 1;
}

.pagination {
    display: flex;
    justify-content: center;
    gap: 0.5em;
    margin: 1em 0;
}

.pagination button {
    padding: 0.5em 1em;
}

.pagination span {
    padding: 0.5em;
}
</style>