<template>
  <nuxt-link
    :to="localizedRoute.fullPath"
    v-bind="$attrs"
    v-on="$listeners"
    @click.native="onClick"
  >
    <slot />
  </nuxt-link>
</template>

<script lang="ts">
import Vue, { PropType } from 'vue';
import { mapMutations } from 'vuex';
import { Location, Route } from 'vue-router';

export default Vue.extend({
  name: 'AppLink',

  props: {
    to: {
      type: [String, Object] as PropType<string | Location>,
      default: '',
    },
    localized: {
      type: Boolean,
      default: false,
    },
  },

  computed: {
    localizedRoute(): Route | undefined {
      return this.localized
        ? this.$router.resolve(this.to).resolved
        : this.localeRoute(this.to);
    },

    isSameRoute(): boolean {
      return (
        !!this.localizedRoute &&
        this.$route.fullPath === this.localizedRoute.fullPath
      );
    },
  },

  methods: {
    ...mapMutations('appLink', ['changeRouterViewKey']),

    onClick() {
      if (this.isSameRoute) {
        this.changeRouterViewKey();
        this.$nuxt.refresh();
      }
    },
  },
});
</script>