/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CoreConfig } from './core-config';

@Injectable({
  providedIn: 'root',
})
export class CoreConfigurationLoaderService {
  private _deferredConfigResolve: (value?: PromiseLike<CoreConfig> | CoreConfig) => void;
  private _deferredConfigReject: (reason?: any) => void;
  public config: Promise<CoreConfig> = new Promise<CoreConfig>((resolve, reject) => {
    this._deferredConfigResolve = resolve;
    this._deferredConfigReject = reject;
  });
  private _loadedConfig: CoreConfig = null;

  constructor(private http: HttpClient, private location: Location) {}

  get loadedConfig() {
    return this._loadedConfig;
  }

  public load(url: string): Promise<CoreConfig> {
    const configFilePath = this.location.prepareExternalUrl(url);
    return this.http
      .get(configFilePath)
      .toPromise()
      .then((config: CoreConfig) => {
        this._deferredConfigResolve(config);
        this._loadedConfig = config;
        return config;
      })
      .catch((error) => {
        console.error('Error loading CoreConfiguration', error);
        this._deferredConfigReject(error);
        return null;
      });
  }
}
