<template>
  <img :src="imageSrc" style="width:100%;height:100%" />
</template>

<script>
import axios from 'axios';

export default {
  name: "AuthedImage",
  props: {
    src: {
      type: String,
      default: function () {
        return undefined;
      },
    },
  },
  unmounted() {
    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">
@use "@/assets/css/chat.scss" as *;
</style>
