import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AppSettings } from 'src/app/model/config/app-settings';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root',
})
export class SettingsService {
  settings!: AppSettings;

  constructor(private http: HttpClient) {}

  loadSettings(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.http
        .get<AppSettings>(`/assets/config/${environment.config}`)
        .pipe(
          catchError(error => {
            reject(error);
            return throwError(() => error);
          })
        )
        .subscribe(settings => {
          this.settings = settings;
          if (this.settings.themes.length === 0) {
            this.settings.themes.push({
              label: 'Open-redirect',
              name: 'open-redirect',
            });
          }
          resolve();
        });
    });
  }
}
