Newer
Older
francois.grand
committed
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
francois.grand
committed
import { Message, MessageCode, Observable } from "jalhyd";
francois.grand
committed
import { StringMap } from "../../stringmap";
francois.grand
committed
import { ServiceFactory } from '../service-factory';
francois.grand
committed
/*
language tag : fr-FR
primary subcode : fr
optional subcode : FR
*/
francois.grand
committed
export enum LanguageCode {
francois.grand
committed
FRENCH,
ENGLISH,
}
francois.grand
committed
export class Language {
private _code: LanguageCode;
private _tag: string;
private _label: string;
constructor(c: LanguageCode, t: string, l: string) {
this._code = c;
this._tag = t;
this._label = l;
}
get code(): LanguageCode {
return this._code;
}
get tag(): string {
return this._tag;
}
get label(): string {
return this._label;
}
}
francois.grand
committed
@Injectable()
export class InternationalisationService extends Observable {
francois.grand
committed
private _currLang: Language;
francois.grand
committed
private _sLang: string;
private _Messages: StringMap;
francois.grand
committed
francois.grand
committed
private _languages: Language[];
francois.grand
committed
public constructor() {
francois.grand
committed
this._languages = [];
this._languages.push(new Language(LanguageCode.FRENCH, "fr", "Français"));
this._languages.push(new Language(LanguageCode.ENGLISH, "en", "English"));
francois.grand
committed
}
francois.grand
committed
public get languages() {
return this._languages;
}
francois.grand
committed
francois.grand
committed
public get currentLanguage() {
return this._currLang;
}
francois.grand
committed
public get currentMap() {
return this._Messages;
}
francois.grand
committed
private getLanguageFromCode(lc: LanguageCode) {
for (let l of this._languages) {
francois.grand
committed
return l;
}
throw new Message(MessageCode.ERROR_LANG_UNSUPPORTED);
francois.grand
committed
}
francois.grand
committed
private getLanguageFromTag(tag: string) {
for (let l of this._languages) {
if (l.tag === tag)
return l;
}
let e = new Message(MessageCode.ERROR_LANG_UNSUPPORTED);
francois.grand
committed
e.extraVar["locale"] = tag;
throw e;
}
francois.grand
committed
public setLocale(lng: string | LanguageCode) {
if (this._currLang !== undefined)
francois.grand
committed
var oldLang: LanguageCode = this._currLang.code;
francois.grand
committed
if (typeof lng === "string") {
let t: string = lng.substr(0, 2).toLowerCase();
this._currLang = this.getLanguageFromTag(t);
}
else {
this._currLang = this.getLanguageFromCode(lng);
francois.grand
committed
let prom = this.httpGetMessages();
prom.then((res) => {
this.notifyObservers(undefined);
})
private httpGetMessages(): Promise<Response> {
francois.grand
committed
let is: InternationalisationService = this;
let processData = function (s: string) {
// fermeture nécessaire pour capturer la valeur de this (undefined sinon)
is._Messages = JSON.parse(s);
francois.grand
committed
}
let l;
francois.grand
committed
switch (this._currLang.code) {
case LanguageCode.FRENCH:
francois.grand
committed
l = "fr";
break;
default:
l = "en";
}
let f: string = "error_messages." + l + ".json"
francois.grand
committed
return ServiceFactory.instance.httpService.httpGetRequest(undefined, undefined, undefined, "locale/" + f, processData);
francois.grand
committed
}
private getMessageFromCode(c: MessageCode): string {
let sCode: string = MessageCode[c];
return this._Messages[MessageCode[c]];
francois.grand
committed
}
private replaceAll(str: string, find: string, replace: string) {
return str.replace(new RegExp(find, 'g'), replace);
}
francois.grand
committed
/**
* traduit un message
* @param r message
* @param nDigits nombre de chiffres à utiliser pour l'arrondi dans le cas de données numériques
*/
public localizeMessage(r: Message, nDigits: number = 3): string {
let sCode: string = MessageCode[r.code];
let m: string = this.getMessageFromCode(r.code);
francois.grand
committed
for (let k in r.extraVar) {
francois.grand
committed
let v: any = r.extraVar[k];
if (typeof v === "number")
var s = v.toFixed(nDigits);
else
s = v;
m = this.replaceAll(m, "%" + k + "%", s);
francois.grand
committed
}
return m;
}
/**
* Traduit un texte défini dans les fichiers error_message.xx.json
* Les ids dans ces fichiers sont soit un enum de JalHyd, soit une chaine libre correspondant au code passé àlocalizeText()
* @param code id du texte
*/
public localizeText(code: string) {
if (this._Messages === undefined) {
return "<messages not loaded>";
}
if (this._Messages[code] === undefined) {
return `<message not exists: ${code}>`;
}
return this._Messages[code];
}
francois.grand
committed
/**
* analyse un libellé du type ouvrage[n].XX
*/
private parseLabel(lbl: string) {
const re = /([A-Z,a-z]+)\[(\d+)\]\.(.+)/;
return re.exec(lbl);
}
/**
* traduit un libellé qui peut être un code
*/
public translateLabel(o: any) {
let res;
if (typeof o === "string") {
switch (o) {
case "flu":
res = this.localizeText("INFO_REMOUSRESULTS_LIGNEFLUVIALE");
break;
case "tor":
res = this.localizeText("INFO_REMOUSRESULTS_LIGNETORRENTIELLE");
break;
default:
francois.grand
committed
const match = this.parseLabel(o);
francois.grand
committed
if (match) {
if (match[1] === "ouvrage")
res = this.localizeText("INFO_OUVRAGE") + " n°" + (+match[2] + 1);
francois.grand
committed
const p = match[3];
switch (p) {
case "Q":
res += " : " + this.localizeText("INFO_GRANDEUR_" + p);
break;
francois.grand
committed
case "Q_Mode":
res += " : " + this.localizeText("INFO_TYPE_ECOULEMENT");
break;
francois.grand
committed
case "Q_Regime":
res += " : " + this.localizeText("INFO_REGIME");
break;
}
}
francois.grand
committed
else
res = o;
break;
}
}
return res;
}
francois.grand
committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* met en forme ou traduit un résultat en fonction du libellé qui l'accompagne
*/
public formatResult(label: string, value: number): string {
const match = this.parseLabel(label);
if (match)
switch (match[1]) {
case "ouvrage":
switch (match[3]) {
case "Q_Mode":
switch (value) {
case 0:
case 1:
case 2:
const key = `INFO_LIB_ENUM_RES_STRUCTURE_MODE_${value}`;
return this.localizeText(key);
default:
throw new Error(`InternationalisationService.formatResult : valeur ${value} incorrecte pour STRUCTURE_MODE`);
}
case "Q_Regime":
switch (value) {
case 0:
case 1:
case 2:
const key = `INFO_LIB_ENUM_RES_STRUCTURE_REGIME_${value}`;
return this.localizeText(key);
default:
throw new Error(`InternationalisationService.formatResult : valeur ${value} incorrecte pour STRUCTURE_REGIME`);
}
}
}
const appSetupService = ServiceFactory.instance.applicationSetupService;
const nDigits = appSetupService.displayDigits;
return value.toFixed(nDigits);
}