<template>
  <div class="avatar" :style="avatarStyle">
    <span v-if="hasStatus" class="avatar-status" :class="statusClassName"></span>
    <slot></slot>
  </div>
</template>

<script>
import md5 from 'crypto-js/md5';

export default {
  name: 'EbAvatar',

  props: {
    name: { required: false, type: String },
    email: { default: null, type: String },
    size: { default: 60, type: [Number, String] },
    image: { required: false, type: String },
    statusColor: { default: '', type: String }
  },

  methods: {
    avatar(name, email = null, size = 80) {
      name = encodeURIComponent(name).replace(/%20/g, '+');

      if (email === null)
        return `https://ui-avatars.com/api?name=${name}&size=${size}`;

      return `https://gravatar.com/avatar/${md5(
        email
      )}?s=${size}&d=${encodeURIComponent(
        `https://ui-avatars.com/api\/${name}\/${size}`
      )}`;
    }
  },

  computed: {
    avatarStyle() {
      return {
        backgroundImage: this.image
          ? `url(${this.image})`
          : `url(${this.avatar(this.name, this.email, this.size)})`
      };
    },

    statusClassName() {
      const className = {};
      className[`bg-${this.statusColor}`] = this.hasStatus;
      return className;
    },

    hasStatus() {
      return this.statusColor !== '';
    }
  }
};
</script>

