<template>
  <a :href="buildHref(to)"><slot/></a>
</template>

<script>

import {getCurrentInstance} from 'vue'
import $ from 'jquery'

export default {
  setup: function() {

    const internalInstance = getCurrentInstance()

    //for some reason useRoute doesnt work in a bundled component
    const route = internalInstance.appContext.config.globalProperties.$route
    const router = internalInstance.appContext.config.globalProperties.$router

    //todo add to Utils to be used for the computed property in component Breadcrumb?
    const getCrumbs = () => {
      const breadcrumbs = []

      route.matched.forEach((part) => {

        if(!part.name && part.children[0].path == ''){
          part = part.children[0]
        }
        if(part.name && (!breadcrumbs[breadcrumbs.length-1] || part.name != breadcrumbs[breadcrumbs.length-1].name)){
          const text = part.meta && part.meta.title ? typeof(part.meta.title) === 'function' ? part.meta.title(route) : part.meta.title : null

          const crumb = {
            name: part.name,
            text
          }
          breadcrumbs.push(crumb)
        }
      })

      return breadcrumbs
    }

    const buildHref = function (to) {
      const q = to.params === undefined ? {} : {...to.params}

      if (to.args !== undefined) {
        q.controller = { args: to.args }
      }
      q.referer_breadcrumb = []

      getCrumbs().forEach((crumb) => {
        q.referer_breadcrumb.push({text: crumb.text, path: router.resolve(crumb).fullPath})
      })

      return to.path + (to.path.includes('?') ? '&' : '?') + $.param(q)
    }

    return {buildHref}
  },
  props: {
    to: {
      type: Object,
      default: function () {
        return {}
      }
    }
  }
}
</script>
