<template>
  <loader>
    <validator-group>
      <new-page-nav :parent-id="page.parentId"/>
      <div class="copy-page-header">
        <page-editor-header :page="page"></page-editor-header>
        <h2>Kopieer van bestaande pagina:</h2>
        <copy-page-picker v-model="pageVersionId"></copy-page-picker>
        <validator :test="!!pageVersionId"></validator>
      </div>
      <bottom-toolbar>
        <submit slot="right" :action="save">
          <span class="icon-floppy-disk"></span>
          Opslaan
        </submit>
      </bottom-toolbar>
      <confirm-dialog ref="dialog"></confirm-dialog>
    </validator-group>
  </loader>
</template>

<style lang="scss" scoped>
  .copy-page-header {
    padding: 15px;
    background: linear-gradient(to bottom, #fff 60%, rgba(255, 255, 255, 0) 100%);
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
  }
</style>

<script>
import pageEditorHeader from './page-editor-header.vue';
import loader from '../shared/loader.vue';
import * as formElements from '../shared/form/all.js';
import newPageNav from './new-page-nav.vue';
import copyPagePicker from './copy-page-picker.vue';
import { pageStore } from '../tools/page-store.js';

export default {
  name: 'new-page-editor',
  data() {
    const {parentId} = this.$router.currentRoute.params;
    return {
      page: {
        name: 'nieuwe-pagina',
        parentId,
      },
      pageVersionId: null,
      isLoading: true
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.isLoading = false;
    });
  },
  beforeRouteLeave(to, from, next) {
    if (this.$refs['version-editor'] && this.$refs['version-editor'].changed) {
      this.$refs.dialog.confirm(
        'De nieuwe pagina is nog niet opgeslagen',
        'Wil je de nieuwe pagina verwijderen?'
      ).then((isConfirmed) => {
        next(isConfirmed);
      });
    } else {
      next();
    }
  },
  methods: {
    save() {
      return pageStore.createFromCopy(this.pageVersionId, this.page.name, this.page.parentId)
      // return pageStore.create(this.pageVersion, this.page.name, this.page.parentId)
        .then(pageVersion => {
          this.$router.push({
            name: 'page-editor-version',
            params: { id: pageVersion.pageId, versionId: pageVersion.id }
          });
        })
        .catch(e => {
          console.error(e);
          this.$store.dispatch('alerts/addError', e.message);
        })
    }
  },
  components: {
    copyPagePicker,
    newPageNav,
    pageEditorHeader,
    loader,
    ...formElements
  }
}
</script>
