<!-- eslint-disable vue/no-deprecated-v-on-native-modifier -->
<template>
  <RouterLink
    :to="routeParamsReady ? toRoute(to.name, { params: routeParams }) : {}"
    @click.native="$event.stopImmediatePropagation()"
  >
    {{ textValue }}
  </RouterLink>
</template>

<script>
import { computed, defineComponent, toRefs } from '@vue/composition-api'
import { get } from 'lodash-es'
import { useTextValueRenderer } from './useTextValueRenderer'

export default defineComponent({
  name: 'RouterLinkRenderer',
  props: {
    item: {
      type: Object,
      required: true,
    },
    // eslint-disable-next-line vue/no-unused-properties
    value: {
      type: [String, Function],
      required: true,
    },
    to: {
      type: Object,
      reuired: true,
    },
  },
  setup(props) {
    const { item, value } = toRefs(props)
    const textValue = useTextValueRenderer(item, value)
    const routeParams = computed(() => {
      if (Array.isArray(props.to.params)) {
        return props.to.params.reduce((params, paramOptions) => {
          return {
            ...params,
            [paramOptions.key]: paramOptions.field ? get(props.item, paramOptions.field) : paramOptions.value,
          }
        }, {})
      }

      return {}
    })
    const routeParamsReady = computed(() =>
      Object.values(routeParams.value).every((keyValue) => keyValue !== undefined)
    )

    function toRoute(name, { params, ...rest } = {}) {
      return {
        name,
        params,
        ...rest,
      }
    }

    return {
      toRoute,
      textValue,
      routeParamsReady,
      routeParams,
    }
  },
})
</script>
