locale.service.ts 2.81 KB
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {MoyaLocale} from './moya-locale.model';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/catch';
import {TranslateService} from '@ngx-translate/core';
import {MOYA_REST_URL} from "../../shared/config/moya.config";


export const ENGLISH = 'en';
export const FINNISH = 'fi';
export const SWEDISH = 'sv';

export const DEFAULT_LOCALE = FINNISH;
const LOCALSTORAGE_NAME = 'currently used locale code';





@Injectable()
export class LocaleService {

  selectedLocale: string;

  constructor(private http: HttpClient, private translate: TranslateService) {
    this.translate.setDefaultLang(ENGLISH);
    this.getUserLocale().subscribe();
  }


  /**
   * Returns same locale you did give this as a parameter.
   *
   * @param {string} locale
   * @param {boolean} save
   * @return {string}
   */
  selectLocale(locale: string, save = false): string {

    if (![ENGLISH, FINNISH, SWEDISH].includes(locale)) {
      return;
    }

    this.translate.use(locale);
    this.selectedLocale = locale;

    if (save) {
      this.setUserLocale(locale);
    }

    return locale;

  }

  /**
   * Order of Locale:
   * 1. User's locale from database
   * 2. User's locale from cookie
   * 3. Event's locale from database
   * 4. Default
   *
   * @return {Observable<string>} Return current locale as a string. No errors.
   */
  public getUserLocale(): Observable<string> {

    // If there is already locale, don't bother of running this rest stuff again
    if (this.selectedLocale) {
      return new Observable<string>(x => x.next(this.selectedLocale));
    }

    return this.http.get<MoyaLocale>(MOYA_REST_URL + '/v3/locale/')
      .catch(x =>
        Observable.of({} as MoyaLocale)
      )
      .map(locale => {
        if (locale && locale.userLocale) {
          return this.selectLocale(locale.userLocale);
        }

        const storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);

        if (storageLocale) {
          return this.selectLocale(storageLocale);
        }

        if (locale.eventLocale) {
          return this.selectLocale(locale.eventLocale);
        }

        return this.selectLocale(DEFAULT_LOCALE);
      });
  }


  /**
   * Store user's locale. This will store it to server.  Or server is not available, into localstorage.
   *
   * There is no errors
   * @param {string} locale
   */
  public setUserLocale(locale: string): void {

    const newLocale: MoyaLocale = {
      userLocale: locale,
      eventLocale: undefined
    };

    // let's save locale to database, if it fails, we save it into localstorage. No errors to show for user.
    this.http.post(MOYA_REST_URL + '/v3/locale/', newLocale).catch(x => {
      localStorage.setItem(LOCALSTORAGE_NAME, locale);
      return 'ok';
    }).subscribe();
  }
}