import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

import { FlashMessage } from './flash-message';
import { Level } from './level';

@Injectable()
export class FlashMessageService {
  private messageSubject: BehaviorSubject<FlashMessage[]>;

  constructor() {
    this.messageSubject = new BehaviorSubject([] as FlashMessage[]);
  }

  public get messages(): Observable<FlashMessage[]> {
    return this.messageSubject.asObservable();
  }

  public add(message: string, level: Level = Level.Primary) {
    const prevValue = this.messageSubject.value;
    prevValue.push({ message, level });
    this.messageSubject.next(prevValue);
  }

  public remove(idx: number) {
    const prevValue = this.messageSubject.value;
    this.messageSubject.next(prevValue.splice(idx, 1));
  }
}
