import { HttpClient, HttpHeaders } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';

import { TranslateLoader } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { environment } from '../../../environments/environment';
import { IValues } from '../interface/setting.interface';
import { SettingState } from '../state/setting.state';

@Injectable({
  providedIn: 'root', // or use providedIn: AppModule if only needed in AppModule
})
export class TranslationLoader implements TranslateLoader {
  private http = inject(HttpClient);

  public lang: string;

  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;

  constructor() {
    this.setting$.subscribe(res => {
      if (res) {
        this.lang = res?.general?.default_language?.locale;
      }
    });
  }

  getTranslation(): Observable<any> {
    // Create headers
    const headers = new HttpHeaders({
      'Accept-Lang': this.lang ? this.lang : 'en',
    });
    console.warn('headers', headers);

    // Pass headers in the HTTP GET request
    return this.http.get<any>(`${environment.URL}/translation/front`, { headers });
  }
}
