import { Observable, ReplaySubject, Subject, Subscription } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
import { NAPError, NAPMessage } from './external-interfaces';

export const createMessageStreams = (): {
  fromHost$: Observable<NAPMessage>;
  toHost$: Subject<NAPMessage>;
  errors$: Observable<NAPError>;
  postError: (error: NAPError) => void;
  setToHostCallback: (callback: (message: NAPMessage) => void) => void;
  postMessageFromHost: (message: NAPMessage) => void;
} => {
  /*
   * Bind the fromHost$ stream to the innerFromHost$ Subject to
   * encapsulate the Subject as an observable.
   */
  const innerFromHost$ = new Subject<NAPMessage>();
  const fromHost$ = innerFromHost$.asObservable().pipe(shareReplay());

  /*
   * Bind the errors$ stream to the innerErrors$ Subject to
   * encapsulate the Subject as an observable.
   */
  const innerErrors$ = new ReplaySubject<NAPError>();
  const errors$ = innerErrors$.asObservable();

  /*
   * A Subject that represents the stream of messages that flows
   * to the host.
   */
  const innerToHost$ = new Subject<NAPMessage>();

  /*
   * A handle to report errors. Reported errors will be partially
   * handled and than send through the errors stream if it is still
   * open.
   */
  const postError = (error: NAPError): void => {
    innerErrors$.next(error);
    if (error.isFatal) {
      innerFromHost$.complete();
      innerToHost$.complete();
    }
  };

  /*
   * Handle to set the callback used to consume the messages that is
   * send through the toHost stream.
   */
  let currentToHostCallbackSubscription: Subscription;
  const setToHostCallback = (
    callback: (message: NAPMessage) => void
  ): void => {
    if (currentToHostCallbackSubscription) {
      currentToHostCallbackSubscription.unsubscribe();
    }
    currentToHostCallbackSubscription = innerToHost$.subscribe(callback);
  };

  /*
   * A handle to post messages to the stream that flows from the host
   */
  const postMessageFromHost = (message: NAPMessage): void => {
    innerFromHost$.next(message);
  };

  /*
   * Public interface of the MessageStreams
   */

  return {
    fromHost$,
    toHost$: innerToHost$,
    errors$,
    postError,
    setToHostCallback,
    postMessageFromHost,
  };
};
