import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import {
  UmgNotiNotification,
  decodeUmgNotiNotification
} from '../protocols/noti';
import { ProtocolService } from '@ucap-webmessenger/protocol';
import { share, filter, tap } from 'rxjs/operators';
import {
  SVC_TYPE_UMG,
  SSVC_TYPE_UMG_NOTI,
  SSVC_TYPE_UMG_DELETE_NOTI
} from '../types/service';
import {
  decodeUmgDeleteNotiNotification,
  UmgDeleteNotiNotification
} from '../protocols/del-noti';

type Notifications = UmgNotiNotification | UmgDeleteNotiNotification;

@Injectable({
  providedIn: 'root'
})
export class UmgProtocolService {
  private notificationSubject: Subject<Notifications>;
  public notification$: Observable<Notifications>;

  constructor(private protocolService: ProtocolService) {
    this.notificationSubject = new Subject();
    this.notification$ = this.notificationSubject.asObservable().pipe(share());

    this.protocolService.serverMessage
      .pipe(
        filter(message => message.serviceType === SVC_TYPE_UMG),
        tap(message => {
          switch (message.subServiceType) {
            case SSVC_TYPE_UMG_NOTI:
              {
                this.notificationSubject.next(
                  decodeUmgNotiNotification(message)
                );
              }
              break;

            case SSVC_TYPE_UMG_DELETE_NOTI:
              {
                this.notificationSubject.next(
                  decodeUmgDeleteNotiNotification(message)
                );
              }
              break;

            default:
              break;
          }
        })
      )
      .subscribe();
  }
}
