import { TranslateLoader } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { NativeService } from '@ucap-webmessenger/native';

export class TranslateLoaderService implements TranslateLoader {
  constructor(
    private nativeService: NativeService,
    private prefix: string = '/assets/i18n/',
    private suffix: string = '.json'
  ) {}

  /**
   * Gets the translations from the server
   */
  public getTranslation(lang: string): Observable<any> {
    return new Observable<any>(subscriber => {
      this.nativeService
        .readFile(`${this.prefix}${lang}${this.suffix}`)
        .then(buffer => {
          subscriber.next(JSON.parse(buffer.toString('utf-8')));
        })
        .catch(reason => {
          subscriber.error(reason);
        })
        .finally(() => {
          subscriber.complete();
        });
    });
  }
}
