import {
  Component,
  OnInit,
  ViewChild,
  Renderer2,
  AfterViewChecked,
  ComponentRef,
  ElementRef,
  ApplicationRef,
  AfterViewInit
} from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Component({
  selector: 'sts-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss']
})
export class AlertComponent implements AfterViewInit {
  public componentRef: ComponentRef<AlertComponent>;
  public message: string;
  public noOfAlerts: Subject<number> = new Subject();
  public alertNo: number;
  public active = true;

  private defaultMargin = 30;
  private timeout = 5000;

  @ViewChild('alert') alert: ElementRef;

  constructor(
    private applicationRef: ApplicationRef,
    private renderer: Renderer2,
    private el: ElementRef
  ) { }

  ngAfterViewInit() {
    this.adjustTop();
  }

  adjustTop() {
    /* to be used in future */
    if (this.active) {
      if (this.alertNo && this.alertNo >= 1) {
        const height = this.alert.nativeElement.offsetHeight;
        const top_a = this.defaultMargin;
        this.renderer.setStyle(
          this.el.nativeElement,
          'top',
          (top_a).toString() + '%'
        );
        this.autoClose();
      } else {
        this.close();
        return;
      }
    }
  }
  autoClose() {
    setTimeout(() => {
      if (this.active) {
        this.removeComponentFromBody(this.componentRef);
      }
    }, this.timeout);
  }

  close() {
    this.active = false;
    this.removeComponentFromBody(this.componentRef);
  }

  removeComponentFromBody(componentRef: ComponentRef<AlertComponent>) {
    this.noOfAlerts.next(this.alertNo++);

    if (componentRef !== null) {
      this.applicationRef.detachView(componentRef.hostView);
      componentRef.destroy();
      componentRef = null;
    }
  }
}
