<template>
  <div>
    <validator-group>
      <field label="Bovenliggende pagina" :class="{ 'should-save': shouldSaveMove }">
        <page-picker v-model="page.parentId" :page-enabled-test="notThisPage" />
        <validator v-if="!withActions" :test="!!page.parentId">
          <p class="text-danger m-0">Bovenliggende pagina is verplicht</p>
        </validator>
      </field>
      <submit v-if="withActions" class="btn btn-primary mb-3" :action="handleMove" :class="{'should-save': shouldSaveMove}">Verplaatsen</submit>
    </validator-group>
    <validator-group>
      <field label="Url-gedeelte" :class="{ 'should-save': shouldSaveRename }">
        <input class="form-control" v-model="page.name">
      </field>
      <submit v-if="withActions" class="btn btn-primary mb-3" :action="handleRename" :class="{'should-save': shouldSaveRename}">Hernoemen</submit>
    </validator-group>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

import * as formElements from '../shared/form/all.js';

export default {
  props: {
    page: {
      type: Object,
      required: true
    },
    withActions: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    ...mapGetters('pages', [
      'types'
    ]),
    shouldSaveMove(){
      return this.page.parentId !== this.page.parentId;
    },
    shouldSaveRename(){
      return this.page.name !== this.name;
    },
    schema() {
      return (this.page.versions && this.page.versions[0] && this.types[this.page.versions[0].$type]) || {};
    }
  },
  methods: {
    ...mapActions('pages', ['move', 'rename']),
    ...mapActions('alerts', ['addSuccess', 'addError']),
    async handleRename() {
      try {
        const updatedPage = await this.rename({ page: this.page, name: this.page.name });

        this.page.name = updatedPage.name;
        await this.addSuccess('De paginanaam is gewijzigd!');
      } catch (e) {
        await this.addError(`De paginanaam wijzigen is niet gelukt! <br> ${e.message}`);
      }
    },
    async handleMove() {
      try {
        const updatedPage = await this.move({ page: this.page, newParentId: this.page.parentId });

        this.page.parentId =  updatedPage.parentId;
        await this.addSuccess('De pagina is verplaatst!');
      } catch (e) {
        await this.addError(`De pagina verplaatsen is niet gelukt! <br> ${e.message}`);
      }
    },
    notThisPage(subPage) {
      return this.page.id === subPage.id ? 'subtree-disabled' : 'enabled';
    }
  },
  components: {
    ...formElements
  }
};
</script>
