import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import { Subscription } from 'rxjs'
import { Alert } from './alert'
import { AlertsService } from './alerts.service'

@Component({
  selector: 'app-alerts',
  templateUrl: './alerts.component.html',
  styleUrls: ['./alerts.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class AlertsComponent implements OnInit {
  public alerts: Array<Alert> = []
  public hasOpenAlert: boolean = false

  private alertsSub: Subscription = new Subscription()

  constructor(private _alertsService: AlertsService) {}

  ngOnInit() {
    this.alertsSub = this._alertsService.alerts.subscribe((alert: Alert) => {
      this.alerts.push(alert)

      this.hasOpenAlert = true

      if (alert.err) {
        console.error(alert.err)
      }
    })
  }

  public onAlertClose() {
    this.hasOpenAlert = this.alerts.some((alert) => !alert.closed)
  }
}
