<template>
  <loader>
    <validator-group>
      <new-page-nav :parent-id="page.parentId"/>
      <div class="new-page-header" :class="{'no-page-type': !pageTypeId}">
        <page-editor-header :page="page"></page-editor-header>
        <select class="form-control" :value="pageTypeId" @change="changePageTypeId">
          <option value="">Kies paginatype</option>
          <option v-for="type in orderedTypes" :value="getPageTypeId(type)" v-if="!type.isSingleton && !type.preventCreate">{{type.title}}</option>
          <option value="">-------------</option>
          <option v-for="type in orderedTypes" :value="getPageTypeId(type)" v-if="type.isSingleton && !type.preventCreate">{{type.title}}</option>
        </select>
        <validator :test="!!pageTypeId"></validator>
      </div>

      <version-editor :version="pageVersion" :state="{}" ref="version-editor" :permissions="permissions"
        v-if="pageVersion && pageVersion.$type != 'Q42.Cms.Core.Domain.Folder, Q42.Cms.Core.Domain'"></version-editor>
      <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>
  .new-page-header {
    padding: 15px;
    background: white;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;

    &.no-page-type {
      background: linear-gradient(to bottom, #fff 60%, rgba(255, 255, 255, 0) 100%);
    }
  }
</style>

<script>
import { permissionStore } from '../tools/permission-store.js';
import { pageStore } from '../tools/page-store.js';
import { initialValue } from '../schema/schema-scripts.js';
import _orderBy from 'lodash/orderBy';
import pageEditorHeader from './page-editor-header.vue';
import modal from '../shared/modal.vue';
import versionEditor from './version-editor.vue';
import loader from '../shared/loader.vue';
import * as formElements from '../shared/form/all.js';
import newPageNav from './new-page-nav.vue';

export default {
  name: 'new-page-editor',
  data() {
    const {parentId} = this.$router.currentRoute.params;
    return {
      page: {
        name: 'nieuwe-pagina',
        parentId,
      },
      pageTypeId: '',
      pageVersion: 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();
    }
  },
  computed: {
    permissions() {
      return {
        ...permissionStore.getPermissions('CmsPage'),
        canDepublish: false
      }
    },
    orderedTypes() {
      return _orderBy(pageStore.types, 'title');
    }
  },
  methods: {
    getPageTypeId(type) {
      return type.properties.$type.enum[0]
    },
    changePageTypeId(evt) {
      const pageTypeId = evt.target.value;
      if (pageTypeId === '') {
        this.pageTypeId = pageTypeId;
        this.pageVersion = null;
      } else {
        const selectedPageType = pageStore.types[pageTypeId];
        this.initializePageVersion(pageTypeId, initialValue(selectedPageType));
      }
    },
    initializePageVersion(pageTypeId, version) {
      this.pageTypeId = pageTypeId;
      this.pageVersion = {
        $type: pageTypeId, // NB: API needs $type to be first!
        publishDate: this.pageVersion && this.pageVersion.publishDate,
        depublishDate: this.pageVersion && this.pageVersion.depublishDate,
        metaIndex: this.pageVersion ? this.pageVersion.metaIndex : true,
        showPostFix: this.pageVersion ? this.pageVersion.showPostFix : true,
        metaFollow: this.pageVersion ? this.pageVersion.metaFollow : true,
        ...version
      };
    },
    openModal() {
      this.$refs.modal.show();
    },
    closeModal() {
      this.$refs.modal.hide();
    },
    save() {
      return pageStore.create(this.pageVersion, this.page.name, this.page.parentId).then(pageVersion => {
        if (this.$refs['version-editor']) {
          this.$refs['version-editor'].changed = false;
          this.$router.push({name: 'page-editor-version', params: { id: pageVersion.pageId, versionId: pageVersion.id }});
        } else {
          this.$router.push({name: 'page-editor', params: { id: pageVersion.page.id }});
        }
      }).catch(e => {
        console.error(e);
        this.$store.dispatch('alerts/addError', 'Pagina aanmaken is niet gelukt!');
      })
    }
  },
  components: {
    newPageNav,
    pageEditorHeader,
    modal,
    versionEditor,
    loader,
    ...formElements
  }
}
</script>
