<template>
  <loader>
    <div class="m-auto col-lg-6">
      <div class="card">
        <div class="card-body">
          <div class="row">
            <h1 class="col-sm-12 mb-4">Pagina {{ pageTitle }}</h1>
          </div>
          <div class="row" v-if="!translate">
            <validator-group class="col-sm-12">
              <copy-page-picker v-model="pageVersionId" :prefilled-page-id="pageId"></copy-page-picker>
            </validator-group>
          </div>
          <div class="row">
            <validator-group class="col-sm-12">
              <field label="Bovenliggende pagina" class="col-sm-12">
                <page-picker v-model="pageParentId"></page-picker>
              </field>
            </validator-group>
          </div>
          <div class="row">
            <validator-group class="col-sm-12">
              <field label="Titel" class="col-sm-12">
                <input class="form-control" v-model="pageName" />
              </field>
            </validator-group>
          </div>
          <div class="row">
            <validator-group class="col-sm-12">
              <field label="Taal" class="form-group col-sm-12">
                <language-picker :languageInfos="languageInfos" :translations="translations" v-model="pageLanguage" />
              </field>
            </validator-group>
          </div>
          <div class="row">
            <validator-group class="col-sm-12">
              <validator :test="!!pageVersionId && !!pageParentId && !!pageName && !!pageLanguage"></validator>
              <div class="form-group row col-sm-12 justify-content-end">
                <div class="d-flex justify-content-end col-sm-8">
                  <submit :action="save">
                    <span class="icon-floppy-disk"></span>
                    Opslaan
                  </submit>
                </div>
              </div>
            </validator-group>
          </div>
        </div>
      </div>
    </div>
  </loader>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { namespace, State } from 'vuex-class';
import { Route } from 'vue-router';
import { getPublishedVersions } from './version-utils';
import loader from '../shared/loader.vue';
import languagePicker from '../shared/form/language-picker.vue';
import { LanguageInfo, Translation } from '../stores/types/TranslationStoreModel';
import ValidatorGroup from '../shared/form/validator-group.vue';
import Validator from '../shared/form/validator.vue';
import Submit from '../shared/form/submit.vue';
import Field from '../shared/form/field.vue';
import PagePicker from '../shared/form/page-picker.vue';
import { Version } from '../types/api';
import copyPagePicker from './copy-page-picker.vue';
import PageApi from '../api/page-api';
import TranslationsApi from '../api/translations-api';

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

export interface pageType {
  properties: {
    $type: {
      enum: string[];
    };
  };
}

@Component({
  components: {
    loader,
    languagePicker,
    Field,
    Submit,
    ValidatorGroup,
    Validator,
    PagePicker,
    copyPagePicker
  },
  async beforeRouteEnter(to: Route, from: Route, next: (to?: ((vm: CopyTranslateNewPage) => any) | void) => void) {
    if (to.params.pageId) {
      const pagePromise = PageApi.getPageById(to.params.pageId);
      const translationsPromise = TranslationsApi.getPageTranslations(to.params.pageId);

      Promise.all([pagePromise, translationsPromise]).then(([page, translations]) => {
        const publishedVersions = getPublishedVersions(page.versions);
        let pageVersionId = '';
        if (publishedVersions.length > 0) {
          pageVersionId = publishedVersions[0].id;
        } else {
          pageVersionId = page.versions[0].id;
        }

        next((vm) => {
          if (vm.translate) {
            vm.translationSetId = page.translationSetId;
            vm.translations = translations;
          }
          vm.pageId = to.params.pageId;
          vm.pageVersionId = pageVersionId;
          vm.pageName = page.name;
          vm.isLoading = false;
        });
      });
    } else {
      next((vm) => {
        vm.isLoading = false;
      });
    }
  }
})
class CopyTranslateNewPage extends Vue {
  isLoading = true;

  translations = [] as Translation[];

  pageVersionId: string | null = null;

  pageId: string | null = null;

  pageName = '';

  pageParentId: string | null = null;

  pageLanguage = '';

  translationSetId: string | null = null;

  version: Version | null = null;

  @Prop({ default: false }) readonly translate!: boolean;

  @State((state) => state.translations.languageInfos)
  readonly languageInfos!: LanguageInfo[];

  @State((state) => state.translations.isLoadingLanguageInfos)
  readonly isLoadingLanguageInfos!: boolean;

  @AlertStore.Action('addCmsError') readonly addCmsError!: Function;

  @PageStore.Action('createFromCopy') readonly createFromCopy!: any;

  async save() {
    try {
      const pageVersion = await this.$store.dispatch('pages/createFromCopy', {
        sourceVersionId: this.pageVersionId,
        name: this.pageName,
        metaTitle: this.pageName,
        parentId: this.pageParentId,
        translationSetId: this.translationSetId,
        language: this.pageLanguage
      });

      this.$router.replace({
        name: 'page-editor',
        params: { id: pageVersion.page.id }
      });
    } catch (e) {
      this.addCmsError(e);
    }
  }

  get pageTitle() {
    return this.translate ? 'vertalen' : 'kopiëren';
  }
}

export default CopyTranslateNewPage;
</script>
