import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { NgIf, NgClass } from '@angular/common';

const ALERT_TEMPLATE = `
  <div class="alert" role="alert" [ngClass]="classes" *ngIf="!closed">
    <button *ngIf="dismissible" class="close" (click)="onClose()" (touch)="onClose()" aria-label="Close">
      <span aria-hidden="true" class="material-icons">cancel</span>
    </button>
    <ng-content></ng-content>
  </div>
  `;

/**
 * BS4 alert component according to eniro style guide
 *
 * @class
 */
@Component({
  selector:   'en-alert',
  template:   ALERT_TEMPLATE
})
export class AlertComponent implements OnInit {
  /**
   * flavor of alert, use one of bootstrap element flavors:
   * primary, secondary, info, warning, danger
   * @public
   * @type {'warning' | 'info' | 'success' | 'danger'}
   */
  @Input() public type: 'warning' | 'info' | 'success' | 'danger' = 'warning';

  /**
   * if true, the dismiss button is displayed and active
   * @public
   * @type {boolean}
   */
  @Input() public dismissible: boolean;

  /**
   * if set, dismiss after <dismissOnTimeout> milliseconds
   * @public
   * @type {number}
   */
  @Input() public dismissOnTimeout: number;

  /**
   * event emitted after dismissing
   * @public
   * @type {EventEmitter<AlertComponent>}
   */
  @Output() public close: EventEmitter<AlertComponent> = new EventEmitter<AlertComponent>(false);

  private closed: boolean;
  private classes: Array<string> = [];

  public ngOnInit(): any {
    this.classes[0] = `alert-${this.type}`;
    if (this.dismissible) {
      this.classes[1] = 'alert-dismissible';
    } else {
      this.classes.length = 1;
    }

    if (this.dismissOnTimeout) {
      setTimeout(() => this.onClose(), this.dismissOnTimeout);
    }
  }

  // todo: mouse event + touch + pointer
  public onClose(): void {
    this.closed = true;
    this.close.emit(this);
  }
}
