<template>
  <div class="py-4 container">
    <h4 class="modal-title">{{redirects.length}} redirect(s)</h4>

    <p>
      De onderstaande redirects hebben dezelfde "van" url als de huidige pagina.<br/>
      Zolang deze pagina gepubliceerd is, wordt er niet geredirect.
    </p>
    <table class="table table-striped">
      <thead>
        <th>Omschrijving</th>
        <th>Start</th>
        <th>Eind</th>
        <th>Redirect naar</th>
        <th>Pagina</th>
      </thead>
      <tbody>
        <redirect-item v-for="redirect in redirects" :redirect="redirect" :key="redirect.id" />
      </tbody>
    </table>
    <p v-if="alertRedirectNeeded">
      Deze pagina heeft geen gepubliceerde versies meer en er zijn geen redirects.<br/>
      Gebruik onderstaande knop om een redirect toe te voegen.
    </p>

    <router-link :to="{name: 'create-redirect', query: createRedirectQuery}" class="btn btn-primary">Maak een redirect aan</router-link>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import RedirectApi from '../api/redirect-api';
import redirectItem from './redirect-item.vue';
// @ts-ignore
import { isDepublished, isPublished } from '../pages/version-utils';
import moment from 'moment';
import { Redirect, VersionedPage } from '../types/api';

export interface RedirectValues {
  from: string;
  description: string;
  startDate?: string;
}

@Component({
  components: {
    redirectItem
  }
})
export default class Redirects extends Vue {
  @Prop(Object) page!: VersionedPage;

  redirects: Redirect[] = [];
  isDeleteError = false;

  mounted() {
    this.getRedirects();
  }

  async getRedirects() {
    this.redirects = await RedirectApi.getRedirects(this.page.id);
  }

  get hasPublishedVersions() {
    return this.page.versions.some(isPublished);
  }

  get hasDepublishedVersions() {
    return this.page.versions.some(isDepublished);
  }

  get alertRedirectNeeded() {
    return !this.hasPublishedVersions && this.hasDepublishedVersions && this.redirects.length == 0;
  }

  get latestDepublishDate() {
    const dates = this.page.versions.map(version => version.depublishDate ? new Date(version.depublishDate).getMilliseconds() : 0);
    return Math.max(...dates);
  }

  get createRedirectQuery() {
    const url = this.page.versions[0].page.url; // this.page.url is not correct when page has a parent.
    const redirectValues: RedirectValues = {
      from: url,
      description: `${url} gedepubliceerd`,
    };
    const startDate = this.latestDepublishDate;
    if (startDate) {
      redirectValues.startDate = moment(Math.max(new Date().getMilliseconds(), new Date(startDate).getMilliseconds())).format();
    }
    return redirectValues;
  }

  @Watch('page')
  onPageChange() {
    this.getRedirects();
  }
}
</script>
