import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, firstValueFrom, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TranslationService {

  private _translations: any = {};
  private _translationsLoaded: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor(private http: HttpClient) {}

  // Change language dynamically
  setLanguage(lang: string) {
    this.http.get(`/lang/${lang}.json`).subscribe({
      next: data => {
        this._translations = data;
        this._translationsLoaded.next(true);
      },
      error: err => {
        this._translations = [];
        this._translationsLoaded.next(true);
      }
    })
  }

  // Observable for checking if language is loaded
  get changed$(): Observable<boolean> {
    return this._translationsLoaded.asObservable();
  }

  // Get a specific translation
  translate(page: string, key: string): string {
    return this._translations[page][key] || key;
  }
}