<template>
  <portal to="modal">
    <modal ref="modal">
      <validator-group>
        <div class="modal-header">
          <h4 class="modal-title">Nieuwe vertaling toevoegen</h4>
        </div>
        <div class="modal-body">
          <slot name="description"></slot>
          <field label="Taal" v-if="selectedLanguage">
            <dropdown-menu :label="selectedLanguage.name" class="d-inline-block position-relative bg-white border rounded" full-width>
              <button class="px-2 py-2 d-flex align-items-center dropdown-item" v-for="language in translatableLanguages" :key="language.key" @click="selectedLanguage = language">
                {{ language.name }}
              </button>
            </dropdown-menu>
          </field>
          <slot name="fields"></slot>
        </div>
        <div class="modal-footer">
          <slot name="actions"></slot>
        </div>
      </validator-group>
    </modal>
  </portal>
</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 Modal from '../modal.vue';

import { SupportedLanguage, Translation } from '../../types/language';

const LanguageStore = namespace('languages');
const AlertStore = namespace('alerts');

@Component({
  components: {
    Modal,
    ...formElements
  }
})
export default class AddTranslationModal extends Vue {
  @Prop({ type: Array, required: true }) readonly translatableLanguages!: SupportedLanguage[];
  @Prop({ type: Array, required: true }) readonly translations!: Translation[];

  @Ref() readonly modal: any;

  @LanguageStore.State('all') allLanguages!: SupportedLanguage[];
  @AlertStore.Action('addError') readonly addError!: (message: string) => void;
  @AlertStore.Action('addSuccess') readonly addSuccess!: (message: string) => void;

  selectedLanguage: SupportedLanguage | null = null;

  open(languageKey?: string) {
    this.selectedLanguage = this.translatableLanguages.length > 0 ? this.translatableLanguages.find(language => language.key === languageKey) || this.translatableLanguages[0] : null;
    this.modal.show();
  }

  close() {
    this.modal.hide();
  }

  async add<T>(translatePromise: Promise<T>) {
    if (!this.selectedLanguage) {
      return;
    }

    try {
      const item = await translatePromise;
      await this.addSuccess(`Vertaling ${this.selectedLanguage.name} aangemaakt!`);

      return item;
    } catch (e) {
      await this.addError(`Vertaling ${this.selectedLanguage.name} toevoegen is niet gelukt! <br> ${e.message}`);
    }
  }
}
</script>
