import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { HttpClient } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
import { ConfigService } from 'src/app/service/config.service';

@Injectable({ providedIn: 'root' })
export class TranslationPreloaderService {
  constructor(
    private translate: TranslateService,
    private http: HttpClient,
    private config: ConfigService
  ) {}

  preloadLanguages(): Promise<void> {
    const loadRequests = this.config.settings.languages.map(async lang => {
      const translations = await lastValueFrom(
        this.http.get(`/assets/i18n/${lang}.json`)
      );
      this.translate.setTranslation(lang, translations, true); // merge = true
    });

    return Promise.all(loadRequests).then(() => {});
  }
}
