1 import {Injectable} from '@angular/core';
2 import {Location} from '@angular/common';
3 import {environment} from '../../environments/environment';
4 import {Observable, of} from 'rxjs';
5 import {CookieService} from 'ngx-cookie';
6 import {IdlObject} from '@eg/core/idl.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
9 @Injectable({providedIn: 'root'})
10 export class LocaleService {
13 private ngLocation: Location,
14 private cookieService: CookieService,
15 private pcrud: PcrudService) {
18 setLocale(code: string) {
19 let url = this.ngLocation.prepareExternalUrl('/');
21 // The last part of the base path will be the locale
22 // Replace it with the selected locale
23 url = url.replace(/\/[a-z]{2}-[A-Z]{2}\/$/, `/${code}`);
25 // Finally tack the path of the current page back onto the URL
26 // which is more friendly than forcing them back to the splash page.
27 url += this.ngLocation.path();
29 // Set a 10-year locale cookie to maintain compatibility
30 // with the AngularJS client.
31 // Cookie takes the form aa_bb instead of aa-BB
32 const cookie = code.replace(/-/, '_').toLowerCase();
33 this.cookieService.put('eg_locale',
34 cookie, {path : '/', secure: true, expires: '+10y'});
36 window.location.href = url;
39 // Returns codes supported for the current environment.
40 supportedLocaleCodes(): string[] {
41 return environment.locales || [];
44 // Returns i18n_l objects matching the locales supported
45 // in the current environment.
46 supportedLocales(): Observable<IdlObject> {
47 const locales = this.supportedLocaleCodes();
49 if (locales.length === 0) {
53 return this.pcrud.search('i18n_l', {code: locales});
56 // Extract the local from the URL.
57 // It's the last component of the base path.
58 // Note we don't extract it from the cookie since using cookies
59 // to store the locale will not be necessary when AngularJS
61 currentLocaleCode(): string {
62 const base = this.ngLocation.prepareExternalUrl('/');
63 const code = base.match(/\/([a-z]{2}-[A-Z]{2})\/$/);
64 return code ? code[1] : '';