<!--
  - Copyright (c) 2022.
  - Author Peter Placzek (tada5hi)
  - For the full copyright and license information,
  - view the LICENSE file that was distributed with this source code.
  -->

<script>
import md5 from "md5";
import {BAvatar} from "bootstrap-vue";

export default {
    props: {
        email: {
            type: String,
            default: undefined
        },
        name: {
            type: String,
            default: undefined
        },
        avatar: {
            type: Object | String,
            default: undefined
        },
        size: {
            type: Number | String,
            default: 50
        },
        online: {
            type: Boolean,
            default: undefined
        }
    },
    computed: {
        isAvatarAvailable() {
            return !!this.avatar;
        },

        isEmailAvailable() {
            return !!this.email && this.email !== '';
        },
        emailAvatarUrl() {
            let size = this.size;
            if(typeof this.size === 'string') {
                size = 150;
            } else {
                if(size < 100) {
                    size = 100;
                }
            }


            const img = [
                `https://www.gravatar.com/avatar/`,
                this.hash || md5(this.email.trim().toLowerCase()),
                `?s=${size}`,
                `&d=retro`,
                `&r=g`
            ];

            return img.join('');
        },

        isNameAvailable() {
            return !!this.name && this.name !== '';
        },
        nameLetters() {
            return this.name.substr(0,2).toUpperCase();
        }
    },
    render(createElement, context) {
        let properties = {
            size: this.size,
            variant: 'dark'
        }

        if(typeof this.online !== 'undefined') {
            properties['badge'] = '';
            properties['badge-variant'] = this.online ? 'success' : 'danger';
        }

        if(this.isAvatarAvailable) {
            if(typeof this.avatar.large !== 'undefined') {
                properties.src = this.$nuxt.$config.apiUrl + '/' + this.avatar.path + this.avatar.large;
            } else if(typeof this.avatar.original !== 'undefined') {
                properties.src = this.$nuxt.$config.apiUrl + '/' + this.avatar.path + this.avatar.original;
            } else {
                properties.src = this.avatar;
            }
        } else if(this.isEmailAvailable) {
            properties.src = this.emailAvatarUrl;
        } else if(this.isNameAvailable) {
            properties.text = this.nameLetters;
        } else {
            properties.text = '?';
        }

        if(typeof properties.text !== 'undefined') {
            properties.variant = 'dark';
        }

        return createElement(BAvatar, {
            props: properties
        })
    }
}
</script>
<style>
.b-avatar .b-avatar-badge {
    min-height: 1rem;
    min-width: 1rem;
}
</style>
