import { Subscription } from 'aurelia-event-aggregator';
import { autoinject, customElement } from "aurelia-framework";
import { UIInternal } from '../../utils/ui-internal';
import { Notification } from "../../model/common-model";
import { Config } from '../../config';

@customElement('ui-notification-alert')
@autoinject
export class UINotificationAlert {
  private timeInMillisecondsBeforeAutoClose: number;

  private unreadNotifications: Array<Notification>;
  private subscription: Subscription;

  constructor(config: Config) {
    this.unreadNotifications = new Array<Notification>();
    this.timeInMillisecondsBeforeAutoClose = config.communicationConfig.uINotificationAlertAutoCloseTimeInMilliseconds;
  }

  public bind() {
    this.subscription = UIInternal.subscribe(NOTIFICATION_PUSHED, (notification: Notification) => {
      this.unreadNotifications.push(notification);
      if (this.timeInMillisecondsBeforeAutoClose > 0) {
        setTimeout(() => {
          this.close(notification);
        }, this.timeInMillisecondsBeforeAutoClose);
      }
    });
  }

  public unbind() {
    this.subscription.dispose();
  }

  private async close(notification: Notification) {
    if (this.unreadNotifications.includes(notification)) {
      this.unreadNotifications.remove(notification);
    }
  }
}

export const NOTIFICATION_PUSHED = "Notification-pushed";