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

@Injectable({
  providedIn: 'root',
})
export class ConfigService {
  settings: AppSettings = {
    termsUrl: '',
    privacyURL: '',
    imprintURL: '',
    themes: [
      {
        label: 'Maxlan',
        name: 'maxlan',
      },
    ],
    loadingScreen: {
      background: '',
      logo: '',
    },
    api: {
      url: '',
      wsUrl: '',
      redirector: '',
    },
    keycloak: {
      url: '',
      realm: '',
      clientId: '',
    },
    languages: ['en', 'de'],
  };

  constructor(private http: HttpClient) {}

  loadSettings(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.http
        .get<AppSettingsFromConfig>(`/assets/config/${environment.config}`)
        .pipe(
          catchError(error => {
            reject(error);
            return throwError(() => error);
          })
        )
        .subscribe(settings => {
          if (settings.themes.length === 0) {
            settings.themes.push({
              label: 'Maxlan',
              name: 'maxlan',
            });
          }
          if (settings.languages?.length === 0) {
            settings.languages = ['en', 'de'];
          }

          this.settings = settings as AppSettings;
          resolve();
        });
    });
  }
}
