import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { AvailableAppModule } from './AppModulesTypes';

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

  constructor(private http: HttpClient) { }

  public getAvailableAppModules() {
    // returns all app modules and indicates the customers for which the user can use the modules
    return this.http.get<AvailableAppModule[]>('/api/v1/modules').pipe(catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // client or network error
      console.error('An error occurred:', error.error.message);
    } else {
      // backend returned an error
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`
      );
    }
    return throwError(
      `An eror occurred`
    );
  }
}
