<template>
  <img v-if="imageSrc" :src="imageSrc" />
</template>

<script>
import axios from 'axios';

export default {
  name: "AuthedImage",
  props: {
    src: {
      type: String,
      default: function () {
        return null;
      },
    },
  },
  destroyed() {
    this.unloadSrc();
  },
  watch: {
    src: {
      immediate: true,
      handler(newValue) {
        this.unloadSrc();
        this.loadSrc();
      }
    }
  },
  data() {
    return {
      imageSrc: null
    }
  },
  methods: {
    loadSrc() {
      if (this.src) {
        if (this.$matrix.useAuthedMedia) {
          axios
            .get(this.src, {
              responseType: "blob", headers: {
                Authorization: `Bearer ${this.$matrix.matrixClient.getAccessToken()}`,
              }
            })
            .then((response) => {
              this.imageSrc = URL.createObjectURL(response.data);
            })
            .catch((err) => {
              console.log("Download error: ", err);
            });
        } else {
          this.imageSrc = this.src;
        }
      }
    },
    unloadSrc() {
      if (this.imageSrc && this.src != this.imageSrc) {
        const url = this.imageSrc;
        this.imageSrc = null;
        URL.revokeObjectURL(url);
      }
    }
  }
};
</script>

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