<template>
  <div class="row">
    <div class="col-sm-12">
      <validator-group>
        <field label="Bovenliggende pagina" :class="{ 'should-save': shouldSaveMove }">
          <div class="form-group">
            <page-picker v-model="parentId" :page-enabled-test-fn="notThisPage" v-if="!isNew" :readonly="schema.preventMove"></page-picker>
            <page-picker v-model="page.parentId" :page-enabled-test-fn="notThisPage" v-else></page-picker>
          </div>
          <div v-if="shouldSaveMove">
            <div class="form-group">
              <div class="form-check">
                <input type="checkbox" class="form-check-input" id="create-redirect" v-model="createRedirect" />
                <label class="form-check-label" for="create-redirect">Maak een redirect aan van de oude url naar deze pagina</label>
              </div>
            </div>
            <button class="btn-save btn btn-primary" @click.prevent="handleMove">Verplaatsen</button>
          </div>
        </field>
      </validator-group>
    </div>
    <div class="col-sm-12">
      <validator-group>
        <field label="Url-gedeelte">
          <div class="form-group">
            <input class="form-control" v-model="name" v-if="!isNew" :readonly="schema.preventRename" />
            <input class="form-control" v-model="page.name" v-else />
          </div>
          <div v-if="shouldSaveRename">
            <div class="form-group">
              <div class="form-check">
                <input type="checkbox" class="form-check-input" id="create-redirect" v-model="createRedirect" />
                <label class="form-check-label" for="create-redirect">Maak een redirect aan van de oude url naar deze pagina</label>
              </div>
            </div>
            <button class="btn-save btn btn-primary" @click.prevent="handleRename">Hernoemen</button>
          </div>
        </field>
      </validator-group>
    </div>
    <div class="col-sm-12">
      <validator-group v-if="showLanguageElements">
        <div class="form-group">
          <field label="Verander taal">
            <language-picker :languageInfos="languageInfos" :translations="translations" :id="page.id" v-model="language" />
          </field>
        </div>
      </validator-group>
    </div>
    <confirm-dialog ref="dialog" confirmButtonClass="btn-success"></confirm-dialog>
  </div>
</template>

<style lang="scss" scoped>
.btn-container {
  display: flex;
  justify-content: flex-end;
}

.btn-save {
  width: 9em;
  margin-bottom: 20px;
  z-index: 2;
}

.page-type {
  float: right;
  font-size: 60%;
  padding-top: 0.5em;
}
</style>

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

import languagePicker from '../shared/form/language-picker.vue';
import formElements from '../shared/form/all';
import confirmDialog from '../shared/form/confirm-dialog.vue';
import PageApi from '../api/page-api';
import { getPublishedVersions } from './version-utils';

export default {
  props: {
    page: {
      type: Object,
      required: true
    },
    isNew: {
      type: Boolean,
      default: false
    },
    translations: {
      type: Array,
      default: Array
    },
    isFolder: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const isPublished = getPublishedVersions(this.page.versions).length > 0;

    return {
      parentId: this.page.parentId,
      name: this.page.name,
      language: this.page.language,
      createRedirect: isPublished
    };
  },
  watch: {
    page() {
      this.parentId = this.page.parentId;
      this.name = this.page.name;
      this.language = this.page.language;
    },
    language() {
      if (this.shouldSaveLanguage) {
        this.setLanguage();
      }
    }
  },
  computed: {
    ...mapGetters('pages', ['types']),
    ...mapState('translations', ['languageInfos']),
    showLanguageElements() {
      return this.translations && this.languageInfos.length > 1 && !this.isFolder;
    },
    shouldSaveMove() {
      return !this.isNew && this.page.parentId != this.parentId;
    },
    shouldSaveRename() {
      return !this.isNew && this.page.name != this.name;
    },
    shouldSaveLanguage() {
      return !this.isNew && this.page.language != this.language;
    },
    schema() {
      return (this.page.versions && this.page.versions[0] && this.types[this.page.versions[0].$type]) || {};
    }
  },
  methods: {
    ...mapActions('pages', ['move', 'rename']),
    ...mapActions('alerts', ['addSuccess', 'addCmsError']),
    setLanguage() {
      this.$refs.dialog
        .confirm(
          'Taal veranderen',
          'Weet je zeker dat je de taal wilt veranderen? Vergeet dan niet deze pagina op de juiste plek in de boom te zetten',
          'Ja, taal veranderen',
          'Nee, huidige taal behouden'
        )
        .then(() => {
          return PageApi.setLanguage(this.page, this.language)
            .then((updatedPage) => {
              this.page.language = this.language = updatedPage.language;
              this.addSuccess('De taalaanpassing is opgeslagen!');
            })
            .catch((e) => this.addCmsError(e));
        })
        .catch((e) => {
          // reset to current language of the page
          this.language = this.page.language;
          throw e;
        });
    },
    async handleRename() {
      try {
        const { page, name, createRedirect } = this;
        const updatedPage = await this.rename({ page, name: slugify(name), createRedirect });

        this.page.name = this.name = updatedPage.name;
        this.page.url = updatedPage.url;
        await this.addSuccess('De paginanaam is gewijzigd!');
      } catch (e) {
        await this.addCmsError(e);
      }
    },
    async handleMove() {
      try {
        const { page, parentId, createRedirect } = this;
        const updatedPage = await this.move({ page, newParentId: parentId, createRedirect });

        this.page.parentId = this.parentId = updatedPage.parentId;
        this.page.url = updatedPage.url;
        await this.addSuccess('De pagina is verplaatst!');
      } catch (e) {
        await this.addCmsError(e);
      }
    },
    notThisPage(subPage) {
      return this.page.id == subPage.id ? 'subtree-disabled' : 'enabled';
    }
  },
  components: {
    ...formElements,
    confirmDialog,
    languagePicker
  }
};
</script>
