import Vue from 'vue';
import VueI18n from 'vue-i18n';
import en from '@/locales/en';
import ru from '@/locales/ru';
import {WFLocalDict, WorkflowServiceApi} from '@openapi/wf';
import { AxiosResponse } from 'axios';
import get from 'lodash/get';

Vue.use(VueI18n);

const wfApi = new WorkflowServiceApi();

const i18n = new VueI18n({
  locale: localStorage.getItem('userLocale') || 'ru',
  messages: {
    en,
    ru,
  }, // set locale messages
  pluralizationRules: {
    /**
     * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
     * @param choicesLength {number} an overall amount of available choices
     * @returns number final choice index to select plural word by
     */
    ru: (choice: number, choicesLength: number) => {
      if (choice === 0) {
        return 0;
      }

      const teen = choice > 10 && choice < 20;
      const endsWithOne = choice % 10 === 1;

      if (choicesLength < 4) {
        return !teen && endsWithOne ? 1 : 2;
      }
      if (!teen && endsWithOne) {
        return 1;
      }
      if (!teen && choice % 10 >= 2 && choice % 10 <= 4) {
        return 2;
      }

      return choicesLength < 4 ? 2 : 3;
    },
  },
  silentTranslationWarn: true,
});

export function applyDicts(scopes: string[]): void {
  for (const scope of scopes) {
    wfApi.getDicts(scope).then(({ data }: AxiosResponse<WFLocalDict>) => {
      if (data) {
        if (get(data, 'en', '{}')) {
          i18n.mergeLocaleMessage('en', get(data, 'en', '{}'));
        }

        if (get(data, 'ru', '{}')) {
          i18n.mergeLocaleMessage('ru', get(data, 'ru', '{}'));
        }
      }
    });
  }
}

export { i18n };
