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

import { Injectable, ElementRef } from '@angular/core';
import { OverlayRef, Overlay } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { Observable, Subject } from 'rxjs';
import { BciLoaderComponent } from './bci-loader.component';
import { CustomOverlay } from './custom-overlay';

@Injectable({
  providedIn: 'root',
})
export class BciLoaderService {
  private loaderSubject = new Subject<boolean>();
  public loaderState = <Observable<boolean>>this.loaderSubject.asObservable();
  private loaderQueueElements: Array<LoaderQueueElement> = [];

  constructor(private overlay: Overlay, private customOverlay: CustomOverlay) {}

  showProgressBar(element?: ElementRef): LoaderQueueElement {
    let overlay: Overlay;
    if (element) {
      this.customOverlay.setContainerElement(element.nativeElement);
      overlay = this.customOverlay;
    } else {
      overlay = this.overlay;
    }
    const overlayRef = overlay.create({
      positionStrategy: overlay.position().global().centerHorizontally().centerVertically(),
      hasBackdrop: true,
    });
    overlayRef.attach(new ComponentPortal(BciLoaderComponent));
    const loaderQueueElement: LoaderQueueElement = {
      id: Date.now(),
      overlayRef,
    };
    this.loaderQueueElements.push(loaderQueueElement);
    this.loaderSubject.next(true);
    return loaderQueueElement;
  }

  hideProgressBar(element: LoaderQueueElement): void {
    const index = this.loaderQueueElements.findIndex((el) => element.id === el.id);
    if (index > -1) {
      const loaderQueueElement = this.loaderQueueElements.splice(index, 1);
      loaderQueueElement[0].overlayRef.detach();
    }
    if (this.loaderQueueElements.length === 0) {
      this.loaderSubject.next(false);
    }
  }
}

export class LoaderQueueElement {
  id: number;
  overlayRef: OverlayRef;
}
