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

import { Observable, Subject } from 'rxjs';

import { RPCSubscriber } from '@loafer/ng-rpc';
import { LoggerService } from '@loafer/ng-logger';

import { Probe } from '@overflow/commons-typescript/model/probe';

export interface ProbeNotify {
  method: string;
  params: Probe;
}

export class ProbeSubscriberSubject extends Subject<ProbeNotify> {

}

@Injectable()
export class ProbeSubscriber {
  private probeSubscriberSubject: ProbeSubscriberSubject;

  public constructor(
    private loggerService: LoggerService,
  ) {
    this.probeSubscriberSubject = new ProbeSubscriberSubject();
  }

  public observable(): Observable<ProbeNotify> {
    return this.probeSubscriberSubject.asObservable();
  }

  private publish(method: string, params: any): void {
    this.probeSubscriberSubject.next({ method: method, params: params });
  }

  @RPCSubscriber({ method: 'ProbeService.onConnect' })
  public onConnect(probe: Probe): void {
    this.loggerService.debug('ProbeService.onConnect probe:', probe);

    this.publish('ProbeService.onConnect', probe);
  }

  @RPCSubscriber({ method: 'ProbeService.onDisconnect' })
  public onDisconnect(probe: Probe): void {
    this.loggerService.debug('ProbeService.onDisconnect noAuthProbe:', probe);

    this.publish('ProbeService.onDisconnect', probe);
  }
}
