import { Injectable } from '@angular/core';

import { filter, tap } from 'rxjs/operators';

import { Store } from '@ngrx/store';

import { ProtocolService } from '@ucap-webmessenger/protocol';
import {
  SVC_TYPE_LOGOUT,
  SSVC_TYPE_LOGOUT_RES,
  SSVC_TYPE_LOGOUT_REMOTE_NOTI,
  decodeLogout,
  decodeLogoutRemoteNotification
} from '@ucap-webmessenger/protocol-authentication';

import * as AuthenticationStore from '../store/account/authentication';

@Injectable()
export class AppNotificationService {
  constructor(
    private protocolService: ProtocolService,
    private store: Store<any>
  ) {}

  public subscribe(): void {
    this.protocolService.serverMessage
      .pipe(
        filter(
          message =>
            message.serviceType === SVC_TYPE_LOGOUT &&
            message.subServiceType === SSVC_TYPE_LOGOUT_RES
        ),
        tap(message => {
          const logoutRes = decodeLogout(message);
          console.log('logoutRes', logoutRes);
          this.store.dispatch(AuthenticationStore.logout());
        })
      )
      .subscribe();

    this.protocolService.serverMessage
      .pipe(
        filter(
          message =>
            message.serviceType === SVC_TYPE_LOGOUT &&
            message.subServiceType === SSVC_TYPE_LOGOUT_REMOTE_NOTI
        ),
        tap(message => {
          const logoutRemoteNoti = decodeLogoutRemoteNotification(message);
          this.store.dispatch(AuthenticationStore.logout());
        })
      )
      .subscribe();
  }
}
