<template>
  <div class="lang-changer field is-horizontal">
    <div class="field-label is-normal">
      <label class="label">Changer de langue</label>
    </div>
    <div class="field-body">
      <div class="field is-narrow">
        <div class="control">
          <div class="select is-fullwidth">
            <select name="lang-changer" v-model="lang">
              <option
                v-for="(locale, k) in locales"
                :key="k"
                :value="locale.code"
              >{{ locale.label }}</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

interface ILocale {
  code: string
  label: string
}

@Component
export default class LangChanger extends Vue {
  @Getter
  public locale!: string
  @Action
  public setLocale!: any
  public lang: string = ''
  public locales: ILocale[] = [
    {
      code: 'en',
      label: 'English'
    },
    {
      code: 'fr',
      label: 'Français'
    }
  ]

  public mounted(): void {
    this.lang = this.locale
  }

  @Watch('lang')
  public onlangChange(locale: string): void {
    if (locale !== this.locale) {
      this.setLocale(locale)
    }
    if (locale !== this.$i18n.locale) {
      this.$i18n.locale = locale
    }
  }

  @Watch('locale', { immediate: true })
  public onLocaleChange(locale: string): void {
    if (locale !== this.lang) {
      this.lang = locale
    }
  }
}
</script>
