<template>
  <multi-language-only>
    <dropdown-menu :label="selectedLabel" right class="d-inline-block position-relative bg-white border rounded">
      <button
        class="p-2 d-flex align-items-center dropdown-item"
        v-for="language in languages"
        :key="language.key"
        @click="switchLanguage(language)"
      >
        {{ language.name }}
      </button>
    </dropdown-menu>
  </multi-language-only>
</template>

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

import DropdownMenu from '../dropdown-menu.vue';
import MultiLanguageOnly from './multi-language-only.vue';
import { SupportedLanguage } from '../../types/language';

const LanguageStore = namespace('languages');

@Component({
  components: {
    DropdownMenu,
    MultiLanguageOnly
  }
})
export default class LanguageSwitch extends Vue {
  @LanguageStore.State('all') languages!: SupportedLanguage[];
  @LanguageStore.State('selected') selectedLanguage!: SupportedLanguage | null;
  @LanguageStore.Action('setSelected') setSelected!: (selected: SupportedLanguage) => Promise<void>;

  async switchLanguage(language: SupportedLanguage) {
    if (language.key === this.selectedLanguage?.key) {
      return;
    }

    await this.setSelected(language);
  }

  get selectedLabel() {
    return this.selectedLanguage?.name || '';
  }
}
</script>
