<template>
  <div v-if="info" class="info-tooltip">
    <!-- .stop & .prevent needed to avoid triggering click on parent -->
    <i @click.stop.prevent="showPopup"></i>

    <popup ref="popup">
      <div v-html="formattedInfoString"></div>
    </popup>
  </div>
</template>

<style lang="scss" scoped>
.info-tooltip {
  display: inline-flex;
}

i {
  cursor: pointer;
  font-style: normal;
  margin-left: 10px;

  &::before {
    content: 'i';
    display: inline-block;
    background: #888;
    color: white;
    border-radius: 50%;
    width: 1.5em;
    height: 1.5em;
    text-align: center;
    font-family: serif;
  }
}
</style>

<script>
import popup from './popup.vue';

export default {
  name: 'info-tooltip',
  props: {
    info: {
      validator: (value) => !value || typeof value == 'string',
      docs: `Voegt een info icoontje toe met een popup tekstje`,
      demoValue: 'Hier kan wat uitleg staan met bijvoorbeeld een link https://q42.nl.'
    }
  },
  methods: {
    showPopup() {
      this.$refs.popup.popupVisible ? this.$refs.popup.hide(event.target) : this.$refs.popup.show(event.target);
    }
  },
  computed: {
    formattedInfoString() {
      if (this.info) {
        // find urls in string and replace with a tag to make them clickable
        const urlRegex = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?/g;
        const newString = this.info.replace(urlRegex, function createLink(link) {
          return '<a href=' + link + " target='_blank'>" + link + '</a>';
        });

        return newString;
      }

      return null;
    }
  },
  components: {
    popup
  }
};
</script>
