/*-------------------------------------------------------------------------------------------------------------- * Copyright (c) insite-gmbh. All rights reserved. * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------------------------*/ import { Observable } from 'rxjs/Rx'; import { Injectable, Inject, EventEmitter } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { InaxConfiguration, ProfileService, Map } from '../../../@inax/common'; import { Subject } from "rxjs/Subject"; import { ITranslation } from "./transport/ITranslation" import { LanguageSubscriber } from "./domain/subscriber"; //based on https://github.com/Valetudox/angular2-translate @Injectable() export class InaxTranslateService { private static _subscribers = new Array(); private _translations: Map = {}; private _language: string = "de-DE"; constructor(private _http: Http, private _configuration: InaxConfiguration, private _profileService: ProfileService, @Inject('translations') trans: any) { this.setTranslations(trans); } public get defaultLanguage(): string { let lcid = sessionStorage.getItem("METADATA_LCID_DEFAULT"); if (lcid) return lcid; return "de-DE"; } public set defaultLanguage(value: string) { sessionStorage.setItem("METADATA_LCID_DEFAULT", value); } public get language(): string { return this._language } public set language(lng: string) { this._language = lng; sessionStorage.setItem("METADATA_LCID", lng); this._changeEvent.emit(lng); } public setTranslations(value: any) { for (var lng in value) { if (value.hasOwnProperty(lng)) this._translations[lng] = this.flatten(value[lng]); } } public determineDefaultLcid() { this.getFirstEntryOfText().subscribe((result: ITranslation) => { if (result != null && result.SourceLcid != null) sessionStorage.setItem("METADATA_LCID_DEFAULT", result.SourceLcid); }) } public addTranslations(value: any) { if (this._translations != null) { for (var lng in value) { if (value.hasOwnProperty(lng)) { let currentLng = this._translations[lng]; let flattened = this.flatten(value[lng]); for (var entry in flattened) { if (!currentLng.hasOwnProperty[lng]) { currentLng[entry] = flattened[entry]; } } } } } else { this.setTranslations(value); } } private _changeEvent: EventEmitter = new EventEmitter(); public get ChangeEvent(){return this._changeEvent;} public determineSupportedLanguages(forceOnline: boolean = false): Observable> { let lcids = sessionStorage.getItem("METADATA_LCIDS"); if (forceOnline || lcids == null) { var accessUrl = this._configuration.buildRestUrl("Translation","GetSupportedLcids"); let headers = this._profileService.addAuthorization(new Headers()); return this._http.get(accessUrl, { headers }).map(res => res.json()); } return Observable.create().subscribe(() => { return lcids }); } public translate(value: string, parameters: Map = {}): string { let hasEntry = (this._translations[this._language] != null && this._translations[this._language][value] != null); if (hasEntry) { let translated = hasEntry ? this._translations[this._language][value] : value; return this.interpolate(translated, parameters); } return value; } public translateOnline(text: string, fromLcid: string = "", toLcid: string = ""): Observable { if (fromLcid == null || fromLcid.length == 0) fromLcid = this.defaultLanguage; if (toLcid == null || toLcid.length == 0) toLcid = this.language; var accessUrl = this._configuration.buildRestUrl("Translation","Translate") + "?fromLcid=" + fromLcid + "&toLcid=" + toLcid; let headers = this._profileService.addAuthorization(new Headers()); if (text != null) accessUrl += "?text=" + text; return this._http.get(accessUrl, { headers }).map(res => res.json()); } public tranlsateManyOnline(texts: Array, fromLcid: string = "", toLcid: string = ""): Observable> { if (fromLcid == null || fromLcid.length == 0) fromLcid = this.defaultLanguage; if (toLcid == null || toLcid.length == 0) toLcid = this.language; let accessUrl = this._configuration.buildRestUrl("Translation","TranslateMany") + "?fromLcid=" + fromLcid + "&toLcid=" + toLcid; let headers = this._profileService.addAuthorization(new Headers()); return this._http.post(accessUrl, JSON.stringify(texts), { headers }).map(res => res.json()); } private getFirstEntryOfText(sourceText: string = ""): Observable { var accessUrl = this._configuration.buildRestUrl("Translation","GetFirstEntryForText"); let headers = this._profileService.addAuthorization(new Headers()); if (sourceText != null) accessUrl += "?sourceText=" + sourceText; return this._http.get(accessUrl, { headers }).map(res => res.json()); } private interpolate(str: string, data: Map): string { try{ return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { var value = data[key]; if (value === undefined) { throw new Error('No value provided for variable ' + str); } else if (typeof value === 'function') { value = value(data); } return value; }); } catch(error){ console.error(`Error while interpolate translation '${str}' error was:${error}`); } return str; } private flatten(obj: any): Map { var result: Map = {}; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if ((typeof obj[i]) == 'object') { var flatObject = this.flatten(obj[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; result[i + '.' + x] = flatObject[x]; } } else result[i] = obj[i]; } return result; } }