import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs";
import { Injectable } from "@angular/core";
import {PermissionProvider} from "../provider/permission.provider";

@Injectable({ providedIn: 'root' })
export class PermissionInterceptor implements HttpInterceptor {
  constructor(private permissionProvider: PermissionProvider) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const permissions = this.permissionProvider.getUserPermissions();

    if (permissions.length > 0) {
      request = request.clone({
                                setHeaders: { 'X-User-Permissions': permissions.join(',') }
                              });
    }

    return next.handle(request);
  }
}