<template>
  <div class="language-picker">
    <select v-model="valueCopy" class="form-control">
      <option v-for="option in options" :value="option.language" v-bind:key="option.language" :disabled="option.isDisabled">
        {{ option.displayName }}
      </option>
    </select>
  </div>
</template>

<script>
import { ValueSyncMixin } from '../value-sync-mixin.js';
import { difference, isNil } from 'lodash';

export default {
  mixins: [ValueSyncMixin],
  props: {
    value: {
      required: true,
      validator: (value) => isNil(value) || typeof value === 'string',
      demoValue: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    translations: {
      required: true,
      type: Array
    },
    languageInfos: {
      required: true,
      type: Array
    },
    id: {
      type: String
    }
  },
  mounted() {
    this.valueCopy = this.value || this.getDefaultValue(this.languageInfos, this.translations);
  },
  computed: {
    options() {
      return this.languageInfos.map((languageInfo) => {
        const translationForlanguageInfo = this.translations.find((t) => t.languageInfo.language === languageInfo.language);
        const isTranslated = !!translationForlanguageInfo && !!translationForlanguageInfo.id;
        const isLanguageOfCurrentItem = isTranslated && translationForlanguageInfo.id === this.id;
        return {
          language: languageInfo.language,
          displayName: languageInfo.displayName,
          isDisabled: isTranslated && !isLanguageOfCurrentItem
        };
      });
    }
  },
  watch: {
    value() {
      if (!this.value) {
        this.valueCopy = this.getDefaultValue(this.languageInfos, this.translations);
      }
    }
  },
  methods: {
    getDefaultValue(languageInfos, translations) {
      const defaultLanguageInfo = languageInfos.find((l) => l.isDefault);
      const defaultLanguage = defaultLanguageInfo && defaultLanguageInfo.language;
      const translatedLanguages = translations.filter((t) => t.id).map((t) => t.languageInfo.language);

      if (translatedLanguages.length === 0) {
        return defaultLanguage;
      }

      if (!translatedLanguages.includes(defaultLanguage)) {
        return defaultLanguage;
      }

      const languages = languageInfos.map((l) => l.language);
      const translatableLanguages = difference(languages, translatedLanguages);

      if (translatableLanguages.length > 0) {
        return translatableLanguages[0];
      }

      // we shouldn't be here, you are translating an item which is already translated in all languages
      return languages[0];
    }
  }
};
</script>
