<template>
  <div class="itf-avatar">
    <div v-if="icon" class="feature-icon d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-2">
      <slot></slot>
    </div>
    <div v-else-if="$slots.content" class="w-100 h-100 rounded-2 text-bg-primary bg-gradient">
      <slot name="content"></slot>
    </div>
    <svg v-else role="none" :style="{ height: `${size}px`, width: `${size}px` }"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">
      <mask :id="`itemphotomask${_uid}`">
        <circle :cx="halfSize" :cy="halfSize" fill="white" :r="halfSize"></circle>
        <circle v-if="statusBadge" :cx="statusPosition" :cy="statusPosition" fill="black" :r="statusSize"></circle>
      </mask>
      <g :mask="`url(#itemphotomask${_uid})`">
        <circle fill="#eeeeee" :cx="halfSize" :cy="halfSize" :r="halfSize"></circle>

        <image v-if="src && isImageLoaded" x="0" y="0" height="100%" preserveAspectRatio="xMidYMid slice" width="100%"
               :style="{ height: `${size}px`, width: `${size}px` }"
               v-bind="{'xlink:href': src}"></image>
        <text  v-else dominant-baseline="central"
               :x="halfSize" :y="halfSize" :font-size="size / 2"
               font-weight="bold" text-anchor="middle">{{ letters }}</text>
        <circle class="shadow" :cx="halfSize" :cy="halfSize" :r="halfSize"></circle>
      </g>
    </svg>
    <div v-if="statusBadge"
         class="status-badge"
         :style="{ bottom: `${statusBadgePosition}px`, right: `${statusBadgePosition}px`, height: `${statusBadgeSize}px`, width: `${statusBadgeSize}px` }">
    </div>
  </div>
</template>
<script>
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';

export default @Component({
  name: 'itfAvatar',
})
class itfAvatar extends Vue {
  @Prop({ type: [String, Number], default: 32 }) size;

  @Prop({ type: String, default: null }) src;

  @Prop({ type: String, default: 'AA' }) letters;

  @Prop({ type: Boolean }) statusBadge;

  @Prop({ type: Boolean }) icon;

  isImageLoaded = false;

  mounted() {
    this.onImageChanged();
  }

  @Watch('src')
  onImageChanged() {
    if (!this.src) {
      return;
    }
    this.isImageLoaded = false;
    const img = new Image();
    img.onload = () => {
      this.isImageLoaded = true;
    };
    img.src = this.src;
  }

  get halfSize() {
    return this.size / 2;
  }

  get statusPosition() {
    return (this.size - this.size / Math.PI / 2);
  }

  get statusBadgePosition() {
    // I don't know the formula :)
    return ((this.size - this.statusSize) * (1 / Math.PI / 2 / 2)) / 2;
  }

  get statusSize() {
    return (this.size / 5.5);
  }

  get statusBadgeSize() {
    return (this.size / 4);
  }

  get photoUrl() {
    return this.photo;
  }
}
</script>
