import { LOCALE_EN } from '../i18n/en';
/* eslint-disable @typescript-eslint/ban-types */
import { LOCALE_ES } from '../i18n/es';
import { LOCALE_PT } from '../i18n/pt';

let CURRENT_LANGUAGE = 'es';

const dictionaries: Record<string, unknown> = {
    es: LOCALE_ES,
    en: LOCALE_EN,
    pt: LOCALE_PT
};

export const i18n = (message: string): string => dictionaries[CURRENT_LANGUAGE][message] as string;

export const i18nF = (message: string): Function =>
    dictionaries[CURRENT_LANGUAGE][message] as Function;

export function i18nWithLanguage(code: string, thunk: () => any): any {
    if (!(code in dictionaries)) {
        throw Error('Invalid language code: ' + code);
    }
    const oldLanguage = CURRENT_LANGUAGE;
    CURRENT_LANGUAGE = code;
    try {
        return thunk();
    } finally {
        CURRENT_LANGUAGE = oldLanguage;
    }
}

export const i18nPosition = (position: { filename: any; line: any; column: any }): string => {
    const msg = i18nF('<position>');
    if (typeof msg === 'string') return msg;
    return msg(position.filename, position.line, position.column);
};
