<template>
  <add-translation-modal ref="translationModal" :translations="translations" :translatable-languages="translatableLanguages">
    <template v-slot:description v-if="fromLanguage">
      <p>Je voegt een nieuwe vertaling toe vanuit het {{ fromLanguage.name }}</p>
    </template>
    <template v-slot:fields>
      <field label="Url-gedeelte">
        <validator :test="!!name"></validator>
        <input class="form-control" v-model="name">
      </field>
    </template>
    <template v-slot:actions>
      <button class="btn btn-light" @click.prevent="close">Annuleren</button>
      <submit :action="add">Toevoegen</submit>
    </template>
  </add-translation-modal>
</template>

<script lang="ts">
import { Component, Prop, Ref, Vue } from 'vue-property-decorator';
import { namespace } from 'vuex-class';

// @ts-ignore
import * as formElements from '../form/all.js';
import { PageTranslation, SupportedLanguage } from '../../types/language';
import { Version } from '../../types/api';
import AddTranslationModal from './add-translation-modal.vue';
import LanguageApi from '../../api/language-api';

const LanguageStore = namespace('languages');

@Component({
  components: {
    AddTranslationModal,
    ...formElements
  }
})
export default class AddPageTranslationModal extends Vue {
  @Prop({ type: Array, required: true }) readonly translatableLanguages!: SupportedLanguage[];
  @Prop({ type: Array, required: true }) readonly translations!: PageTranslation[];
  @Prop({ type: String, required: true }) readonly versionId!: string;
  @Prop({ type: String, required: true }) readonly languageRef!: string;
  @Prop({ type: String }) readonly pageId!: string;

  @Ref() readonly translationModal!: AddTranslationModal;

  name = '';

  @LanguageStore.State('all') readonly allLanguages!: SupportedLanguage[];

  open(languageKey?: string) {
    this.translationModal.open(languageKey);
  }

  close() {
    this.translationModal.close();
  }

  async add() {
    const { selectedLanguage } = this.translationModal;
    if (!this.versionId || !this.languageRef || !this.name || !selectedLanguage) {
      return;
    }

    await this.translationModal.add<Version>(LanguageApi.translatePage(this.versionId, selectedLanguage.key, this.name));

    this.$emit('add', selectedLanguage);
    this.close();
  }

  get fromLanguage() {
    const fromTranslation = this.translations.find(translation => translation.pageId === this.pageId);
    return this.allLanguages.find(language => language.key === fromTranslation?.language);
  }
}
</script>
