import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { map } from 'rxjs/operator/map';

import {
  RxWebsocketSubject,
  RxWebsocketSubjectConfig,
} from './RxWebsocketSubject';

import { RPCClientRWC } from '../../RPCClientRWC';

export class RPCClientWebsocketRWC implements RPCClientRWC {
  private _wsSocketSubject: RxWebsocketSubject<Object>;
  private _responseSubject: Subject<Object>;

  public constructor(
    private _config: RxWebsocketSubjectConfig,
  ) {
    this._wsSocketSubject = new RxWebsocketSubject<Object>(this._config);
  }

  public connect(queryString?: string): void {
    if (undefined !== queryString) {
      this._wsSocketSubject.queryString = queryString;
    }
    this._wsSocketSubject.connect();
    this._wsSocketSubject.subscribe(
      (value: Object) => {
        if (undefined !== this._responseSubject) {
          this._responseSubject.next(value);
        }
      },
      (error: any) => {
        if (undefined !== this._responseSubject) {
          this._responseSubject.error(error);
        }
      },
      () => {
        console.log('sss');
      }
    );
  }

  public disconnect(): void {
    this._wsSocketSubject.disconnect();
  }

  public connectionStatus(): Observable<boolean> {
    return this._wsSocketSubject.connectionStatus;
  }

  public readResponse(): Observable<Object> {
    if (undefined === this._responseSubject) {
      this._responseSubject = new Subject<Object>();
    }
    return this._responseSubject.asObservable();
  }

  public writeRequest(data: any): void {
    this._wsSocketSubject.write(data);
  }
}
