import {OverlayContainer} from "ngx-toastr";
import {Inject, Injectable} from "@angular/core";
import {DOCUMENT} from "@angular/common";

@Injectable({ providedIn: 'root' })
export class MfeOverlayContainer extends OverlayContainer {

  constructor(@Inject(DOCUMENT) _document: any) {
    super(_document);
  }

  ngOnDestroy() {
    super.ngOnDestroy();
  }

  protected _createContainer(): void {
    super._createContainer();
    this.appendToRootComponent();
  }

  private appendToRootComponent(): void {
    if (!this._containerElement) {
      return;
    }

    const rootElement = this.getRootElement();
    const parent = rootElement || this._document.body;
    parent.appendChild(this._containerElement);
  }

  private getRootElement(): Element {
    return this._document.querySelector('mfe-webbpm')
        .shadowRoot.querySelector('[webbpm]');
  }
}
