<template>
  <div class="infogram-block">
    <iframe
      :src="src"
      :title="title"
      :height="height"
      class="infogram-block__iframe"
      scrolling="no"
      frameborder="0"
      style="border:none;"/>
  </div>
</template>

<script>
  export default {
    props: ['value'],

    data() {
      return {
        height: 0
      };
    },

    computed: {
      src() {
        return `https://e.infogram.com/${this.id}?src=embed`;
      },
      href() {
        return `https://infogram.com/${this.id}`;
      },
      id() {
        return this.value.id;
      },
      title() {
        return this.value.title || 'Infografik';
      }
    },

    mounted() {
      // from https://developers.infogr.am/oembed/
      window.addEventListener('message', event => {
        try {
          const data = JSON.parse(event.data);
          if (data.context === 'iframe.resize' && this.parseId(data.src) === this.id) {
            this.height = data.height;
          }
        } catch (e) {
          return false;
        }
      });
    },

    methods: {
      parseId(src) {
        // src will be in the format of something like https://e.infogram.com/0ccf86bc-1afe-4026-b313-1f1b5992452b?src=embed
        let last = src.split('/').pop();
        return last.substring(0, last.indexOf('?')); // we're only interested in the id part before the '?'
      },
      openFullscreen() {
        this.$store.dispatch('showFullscreenInfographic', {
          id: this.value.id,
          type: 'infogram-block'
        });
      }
    },
  };
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .infogram-block {
    margin-bottom: $large-spacing;

    &__link {
      text-decoration: none;
      cursor: pointer;
    }

    &__iframe {
      width: 100%;
    }
  }
</style>
