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

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

const LanguageStore = namespace('languages');

@Component
export default class EntityTranslationsProvider<T extends BaseTranslation> extends Vue {
  translateCall: (() => Promise<T[]>) | null = null;
  translations: T[] = [];
  initialized = false;
  loading = false;

  @LanguageStore.State('selected') selectedLanguage!: SupportedLanguage;
  @LanguageStore.Action('setSelected') setSelectedLanguage!: (selected: SupportedLanguage) => Promise<void>;

  async initialize(translateCall: () => Promise<T[]>) {
    this.translateCall = translateCall;
    await this.update();
    this.initialized = true;
  }

  async update(newLanguage?: SupportedLanguage) {
    this.loading = true;
    this.translations = await this.translateCall?.() || [];
    this.loading = false;

    // Wait for the updated translations to propagate to child components to handle the language switch correctly
    await this.$nextTick();

    if (newLanguage && this.selectedLanguage.key !== newLanguage.key) {
      await this.setSelectedLanguage(newLanguage);
    }
  }

  getTranslationByKey(key: string): T | undefined {
    return this.translations.find(translation => translation.language === key);
  }
}
</script>
