<template>
    <div>
        <h2>{{ $t('settings.interests.title') }}</h2>
        <div><span v-for="interest, key in this.userInterests" class="interest">{{ key > 0 ? ', ' : '' }}{{
                getInterestTranslation(interest.user_interest_type) }}<span class="link remove" @click="removeInterest(interest)">-</span></span></div>
    </div>
    <div class="new-interest">
        {{ $t('settings.interests.new') }} <input type="text" v-model="newInterest" @keyup="newInterestKeyupHandler" />
        <button @click="addInterestByText">{{ $t('settings.interests.add') }}</button>
        <div class="new-interest-proposals" v-if="filteredInterests.length > 0">
            <ul>
                <li v-for="interest in filteredInterests" @click="addInterest(interest)" class="link">{{
                    getInterestTranslation(interest) }}</li>
            </ul>
        </div>
    </div>
    <MessageboxWidget :type="messageboxType" :message="messageboxMessage" ref="messageboxWidget"></MessageboxWidget> 
</template>

<script>
import apiClient from '@/utils/axios.js';
import { mapGetters } from 'vuex';
import MessageboxWidget from '../../components/MessageboxWidget.vue';

export default {
    name: "InterestsView",
    components: {
        MessageboxWidget,
    },
    computed: {
        ...mapGetters(['user', 'language']),
    },
    async mounted() {
        await this.loadUserInterests();
    },
    data() {
        return {
            possibleInterests: [],
            userInterests: [],
            filteredInterests: [],
            newInterest: '',
            messageboxType: 'info',
            messageboxMessage: '',
        }
    },
    methods: {
        async loadUserInterests() {
            const resultPossibleInterests = await apiClient.get('/api/settings/getpossibleinterests');
            this.possibleInterests = resultPossibleInterests.data;
            const resultUserInterests = await apiClient.get('/api/settings/getuserinterests');
            this.userInterests = resultUserInterests.data;
        },
        newInterestKeyupHandler() {
            const searchTerm = this.newInterest.toLowerCase();
            this.filteredInterests = [];
            if (searchTerm.length < 2) {
                return;
            }
            this.filteredInterests = this.possibleInterests.filter(interest => {
                if (interest.name.toLowerCase().includes(searchTerm)) {
                    return true;
                }
                if (interest.interest_translations && interest.interest_translations.length > 0) {
                    return interest.interest_translations.some(translation => {
                        return translation.translation.toLowerCase().includes(searchTerm);
                    });
                }
                return false;
            });
        },
        getInterestTranslation(interest) {
            if (interest.interest_translations && interest.interest_translations.length > 0) {
                let translation = interest.interest_translations.filter(translation => {
                    return translation.user_param_value.value === this.language;
                });
                if (translation.length === 0) {
                    translation = interest.interest_translations.filter(translation => {
                        return translation.user_param_value.value === 'en';
                    });
                    if (translation.length === 0) {
                        translation = interest.interest_translations.filter(translation => {
                            return translation.user_param_value.value === 'de';
                        });
                    }
                }
                return translation.length > 0 ? translation[0].translation : interest.name;
            }
            return interest.name; 
        },
        async addInterest(interest) {
            if (!this.userInterests.includes(interest)) {
                try {
                    await apiClient.post('/api/settings/setinterest', { interestid: interest.id });
                    await this.loadUserInterests();
                    this.newInterest = '';
                    this.filteredInterests = [];
                } catch (error) {
                    this.messageboxType = 'error';
                    this.messageboxMessage = $t('settings.interests.errorsetinterest')
                    this.$refs.messageboxWidget.open();
                }
            }
        },
        async addInterestByText() {
            if (this.newInterest.length > 0) {
                const newInterest = this.possibleInterests.filter(interest => this.getInterestTranslation(interest) === this.newInterest);
                if (newInterest.length === 1) {
                    this.addInterest(newInterest[0]);
                    return;
                }
                try  {
                    await apiClient.post('/api/settings/addinterest', {
                        name: this.newInterest
                    });
                    this.messageboxType = 'info';
                    this.messageboxMessage = this.$t('settings.interests.added');
                } catch (error) {
                    this.messageboxType = 'error';
                    this.messageboxMessage = this.$t('settings.interests.adderror');
                }
                this.$refs.messageboxWidget.open();
            }
        },
        async removeInterest(interest) {
            await apiClient.get('/api/settings/removeinterest/' + interest.id);
            await this.loadUserInterests();
        },
    }
}
</script>

<style lang="scss" scoped>
.new-interest {
    position: relative;
}
.new-interest-proposals {
    position: absolute;
    top: 1.5em;
    left: 0;
    border: 1px solid #000000;
    padding: 3px;
    background-color: #ffffff;
}
.new-interest-proposals > ul {
    margin: 0;
    list-style: none;
    padding: 0;
    
}
.interest {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
}
.remove {
    background-color: #ff0000;
    border: 1px solid #000000;
    font-size: 8pt;
    border-radius: 3px;
    color: #ffffff;
    width: 10px;
    height: 10px;
    display: inline-block;
    padding: 0;
    line-height: 8px;
    text-align: center;
    margin-left: 3px;
}
</style>