<template>
  <div class="seen-by-container">
    <v-tooltip top open-delay="500" v-if="seenBy.length > 0">
      <template v-slot:activator="{ on, attrs }">
        <div v-bind="attrs" v-on="on" class="clickable">
          <div class="more" v-if="seenBy.length > 0">{{ moreItems }}</div>
          <transition-group name="list" tag="div" v-if="seenBy.length > 0">
            <v-avatar v-for="(member, index) in seenBy" :key="member.userId" class="seen-by-user" size="16" color="grey"
              v-show="index < SHOW_LIMIT">
              <img v-if="memberAvatar(member)" :src="memberAvatar(member)" />
              <span v-else class="white--text headline">{{
                member.name.substring(0, 1).toUpperCase()
              }}</span>
            </v-avatar>
          </transition-group>
        </div>
      </template>
      <span>{{ $tc("message.seen_by", seenBy.length) }}</span>
    </v-tooltip>
  </div>
</template>

<script>
export default {
  props: {
    room: {
      type: Object,
      default: function () {
        return null;
      },
    },
    event: {
      type: Object,
      default: function () {
        return null;
      }
    },
  },
  data() {
    return {
      seenBy: [],
      SHOW_LIMIT: 5,
    }
  },
  mounted() {
    this.update();
    if (this.room) {
      this.room.on("Room.receipt", this.onReceipt);
    }
  },
  beforeDestroy() {
    if (this.room) {
      this.room.off("Room.receipt", this.onReceipt);
    }
  },
  computed: {
    moreItems() {
      if (this.seenBy.length > this.SHOW_LIMIT) {
        return `+${this.seenBy.length - this.SHOW_LIMIT}`;
      }
      return "";
    }
  },
  methods: {
    onReceipt(ignoredevent) {
      this.update();
    },
    memberAvatar(member) {
      if (member) {
        return member.getAvatarUrl(
          this.$matrix.matrixClient.getHomeserverUrl(),
          16,
          16,
          "scale",
          true
        );
      }
      return null;
    },
    update() {
      this.seenBy = ((this.room && this.event) ? this.room.getReceiptsForEvent(this.event) : [])
        .filter(receipt => receipt.type == 'm.read' && receipt.userId !== this.$matrix.currentUserId)
        .map(receipt => this.room.getMember(receipt.userId));
    },
  },
  watch: {
    event() {
      this.update();
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/chat.scss";
</style>