moya-locale.service.ts 1.8 KB
import { Injectable } from '@angular/core';
import {MoyaRestService} from "../../shared/services/moya-rest.service";
import {Observable} from "rxjs/Observable";
import {MoyaLocale} from "./moya-locale.model";

export const DEFAULT_LOCALE = "fi";
const LOCALSTORAGE_NAME = "currently used locale code";


@Injectable()
export class MoyaLocaleService {


  constructor(private moyaRest : MoyaRestService) { }


  /**
   * 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> {
    return this.moyaRest.get("/v3/locale/").catch(x => null ).map(untypedLocale => {

      const locale = untypedLocale as MoyaLocale;

      if (locale && locale.userLocale) {
        return locale.userLocale;
      }

      let storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);

      if(storageLocale) {
        return storageLocale;
      }

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

      return 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
   * @return {Promise<any>} This will return promise, but it will contain nothing.
   */
  public setUserLocale(locale: string): Observable<any> {

    let newLocale: MoyaLocale = new MoyaLocale();

    newLocale.userLocale = locale;

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


}