<template>
  <div
    class="snt-link">
    <slot
      :label="label"
      :to="to"
      :href="fullHref"
      :target="target">
      <template v-if="to">
        <router-link
          v-slot="{ href: internalHref, navigate }"
          :to="to"
          custom>
          <a
            :href="internalHref"
            :target="target"
            class="snt-link__link"
            @click="navigate">
            <slot
              name="activator"
              :label="label">
              {{ label }}
            </slot>
          </a>
        </router-link>
      </template>
      <a
        v-else
        :href="fullHref"
        :target="target"
        class="snt-link__link">
        <slot
          name="activator"
          :label="label">
          {{ label }}
        </slot>
      </a>
    </slot>
  </div>
</template>

<script>
export default {
  name: 'SntLink',
  props: {
    label: {
      type: [String, Number],
      default: ''
    },
    href: {
      type: String,
      default: ''
    },
    to: {
      type: [String, Object],
      default: undefined
    },
    target: {
      type: String,
      default: '_self'
    }
  },
  data () {
    return {

    }
  },
  computed: {
    fullHref () {
      const href = this.href
      return this.validURL(href) ? href : `${window.location.href}${href}`
    }
  },
  mounted () {

  },
  methods: {
    validURL (str) {
      const pattern = new RegExp('^(https?:\\/\\/)?' // protocol
        + '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' // domain name
        + '((\\d{1,3}\\.){3}\\d{1,3}))' // OR ip (v4) address
        + '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' // port and path
        + '(\\?[;&a-z\\d%_.~+=-]*)?' // query string
        + '(\\#[-a-z\\d_]*)?$', 'i') // fragment locator
      return !!pattern.test(str)
    }
  }
}
</script>

<style scoped>
  .snt-link {
    padding: 0.25em;
  }
  .snt-link__link {
    text-decoration: none;
    height: 100%;
    width: 100%;
  }
</style>
