/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Injectable } from '@angular/core';
import { ThemePalette } from '@angular/material/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SidebarNavItem } from '../layout';
import { ModalWindowService } from '../modal-window/modal-window.service';
import { NotificationTypes } from '../notification/notification.models';
import { NotificationService } from '../notification/notification.service';
import { BciMessagesComponent } from './bci-messages.component';
import { BciMessagesIntl } from './messages-intl';

@Injectable({
  providedIn: 'root',
})
export class BciMessagesService {
  badgeText: Observable<number | string>;
  badgeColor: Observable<ThemePalette>;

  constructor(
    public messagesIntl: BciMessagesIntl,
    private modalWindowService: ModalWindowService,
    private notificationService: NotificationService
  ) {
    const sessionNotifications = this.notificationService.getSessionNotifications().pipe(
      map((notifications) => notifications || []),
      map((notifications) => notifications.map((nf) => nf.type))
    );

    this.badgeText = sessionNotifications.pipe(
      map((notifications) => notifications.length),
      map((length) => {
        if (length === 0) {
          return undefined;
        }
        return length > 999 ? '999+' : length;
      })
    );

    this.badgeColor = sessionNotifications.pipe(
      map((notifications) => {
        if (notifications.indexOf(NotificationTypes.Error) !== -1) {
          return 'warn';
        }
        if (notifications.indexOf(NotificationTypes.Warning) !== -1) {
          return 'accent';
        }
        return 'primary';
      })
    );
  }

  sidebarLink(): SidebarNavItem {
    return {
      id: 'nav-messages',
      title: this.messagesIntl.title,
      cb: () => this.onMessages(),
      icon: 'Bosch-Ic-alarm',
      iconBadgeText: this.badgeText,
      iconBadgeColor: this.badgeColor,
    };
  }

  onMessages() {
    this.modalWindowService.openDialogWithComponent(BciMessagesComponent, {
      width: '800px',
    });
  }
}
