<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: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';

import Submit from '../form/submit.vue';
import { ItemTranslation, SupportedLanguage } from '../../types/language';
import AddTranslationModal from './add-translation-modal.vue';
import LanguageApi from '../../api/language-api';
import { CrudStoreItemsModel } from '../../stores/types/CrudStoreModel';

const LanguageStore = namespace('languages');

@Component({
  components: {
    AddTranslationModal,
    Submit
  }
})
export default class AddItemTranslationModal extends Vue {
  @Prop({ type: Array, required: true }) readonly translations!: ItemTranslation[];
  @Prop({ type: Array, required: true }) readonly translatableLanguages!: SupportedLanguage[];
  @Prop({ type: String, required: true }) readonly module!: string;
  @Prop({ type: String, required: true }) readonly itemId!: string;
  @Prop(Boolean) readonly fromEmpty!: boolean;

  @Ref() readonly translationModal!: AddTranslationModal;

  @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.itemId || !selectedLanguage) {
      return;
    }

    await this.translationModal.add<CrudStoreItemsModel>(LanguageApi.translateItem(this.itemId, selectedLanguage.key, this.module));

    this.$store.commit(`${this.module}/language`, '');
    this.$emit('add', selectedLanguage);
    this.close();
  }

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