import {
  Component,
  Input,
  Output,
  EventEmitter,
  AfterViewInit
} from 'angular2/core';
import {Store} from '@ngrx/store';
import {NotificationActions} from '../actions/actions';
import {Notification} from '../interfaces/notification.interface';

import 'rxjs/add/operator/do';

const styles = require<string>('./notification.styl');
console.log(styles);

@Component({
  selector: 'hx-notify',
  styles: [styles],
  template: `
    <div class="notifications">
      <div class="notification {{ notification.type }}" *ngFor="#notification of notifications | async ">
        <span class="message">{{ notification.message }}</span>
      </div>
    </div>
  `,
  providers: [NotificationActions]
})
export class Notifications implements AfterViewInit {
  @Input() removeDelay: number;
  @Input() location: string;
  @Output() onRemove = new EventEmitter();
  notifications;

  constructor(public store: Store<any>, public actions: NotificationActions) {
    this.notifications = store.select('notifications');
  }

  ngAfterViewInit() {
    this.notifications
    .subscribe(notifications => {
      this.autoRemoveNotifications(notifications);
    });
  }

  autoRemoveNotifications(notifications: Notification[] = []) {
    if (!notifications.length) {
      return;
    }
    setTimeout(() => {
      notifications.forEach(notification => {
        this.removeNotification(notification.id);
        this.onRemove.next(notification);
      });
    }, this.removeDelay);
  }

  removeNotification(id:string) {
    this.actions.clearNotification(id);
  }
}
