<template>
  <router-link class="btn mr-n2" :to="{ path: userEditPath }">
    <div v-if="!avatarUrl && placeholder" class="avatar d-flex justify-content-center align-items-center">
      <account-icon />
    </div>
    <img v-else-if="avatarUrl" :src="avatarUrl" class="avatar" :alt="activeUser.email">
    <span class="ml-2" v-if="$slots.default">
      <slot></slot>
    </span>
  </router-link>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

import { User } from '../types/api';
import { getPreviewUrlForAsset } from '../api/asset-api-helpers';

const DataStore = namespace('data');

@Component
export default class UserAvatar extends Vue {
  @Prop(Object) readonly user!: User;
  @Prop(Boolean) readonly placeholder!: boolean;

  @DataStore.State('currentUser') readonly currentUser!: User;

  get avatarUrl(): string | null {
    return this.activeUser?.avatar ? getPreviewUrlForAsset(this.activeUser.avatar) : null;
  }

  get userEditPath() {
    return this.activeUser ? `/cmsUser/${this.activeUser.id}` : '';
  }

  get activeUser() {
    return this.user || this.currentUser;
  }
}
</script>

<style lang="scss" scoped>
@import '../variables';

.avatar {
  $avatar-size: 36px;

  width: $avatar-size;
  height: $avatar-size;
  object-fit: cover;
  border-radius: 50%;
  background: $body-bg;

  .material-design-icon svg {
    fill: rgba(0, 0, 0, .5);
  }
}
</style>
