<template>
  <loader class="h-100" :is-loading="isLoading">
    <page-bread-crumbs class="mb-3" :page="page" />
    <validator-group v-if="initialized">
      <field label="Bestaande pagina kopiëren">
        <copy-page-picker v-model="pageVersionId" :initial-id="pageCopyId"></copy-page-picker>
        <validator :test="!!pageVersionId"></validator>
      </field>
      <submit :action="copy">Kopiëren</submit>
    </validator-group>
  </loader>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

// @ts-ignore
import * as formElements from '../shared/form/all.js';
import Loader from '../shared/loader.vue';
import CopyPagePicker from './copy-page-picker.vue';
import PageBreadCrumbs from './page-bread-crumbs.vue';

// @ts-ignore
import { CreatePageFromCopyPayload, Page, Version } from '../types/api';
import { Route } from 'vue-router';
import { RawLocation } from 'vue-router/types/router';
import Validator from '../shared/form/validator.vue';
import RouteUtils, { createRoute, ROUTES } from '../tools/route-utils';

const PageStore = namespace('pages');
const AlertStore = namespace('alerts');

@Component({
  components: {
    Validator,
    PageBreadCrumbs,
    Loader,
    CopyPagePicker,
    ...formElements
  },
  beforeRouteEnter(to: Route, from: Route, next: (to?: RawLocation | false | ((vm: CopyPageEditor) => any) | void) => void) {
    next(vm => {
      vm.isLoading = false;
    });
  },
})
export default class CopyPageEditor extends Vue {
  pageVersionId: string | null = null;
  pageCopyId: string | null = null;
  isLoading = true;
  page: Partial<Page> = {
    name: '',
    parentId: null,
  }

  @PageStore.State('initialized') readonly initialized!: boolean;
  @PageStore.Getter('types') readonly types!: any;
  @PageStore.Action('createFromCopy') readonly createFromCopy!: (payload: CreatePageFromCopyPayload) => Promise<Version>;
  @AlertStore.Action('addError') readonly addError!: (message: string) => void;

  beforeMount() {
    const { id } = this.$route.params;
    const { parentId, copyName } = this.$route.query;

    if (parentId && typeof parentId === 'string') {
      this.page.parentId = parentId;
    }

    if (id) {
      this.pageCopyId = id;
      this.page.name = `${copyName}-kopie`;
    }
  }

  async copy() {
    try {
      const pageVersion = await this.createFromCopy({ sourceVersionId: this.pageVersionId, name: this.page.name, parentId: this.page.parentId } as any);
      await RouteUtils.push(createRoute(ROUTES.PAGE_EDITOR_VERSION, { id: pageVersion.pageId, versionId: pageVersion.id }));
    } catch (e) {
      await this.addError(e.message);
    }
  }
}
</script>
