import { Injectable } from '@angular/core';
import { ProtocolService } from '@ucap-webmessenger/protocol';

import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';

import {
  PingRequest,
  PingResponse,
  encodePing,
  decodePing
} from '../protocols/ping';
import { SVC_TYPE_PING, SSVC_TYPE_PING_REQ } from '../types/service';

@Injectable({
  providedIn: 'root'
})
export class PingProtocolService {
  constructor(private protocolService: ProtocolService) {}

  public ping(req: PingRequest): Observable<PingResponse> {
    return this.protocolService
      .call(SVC_TYPE_PING, SSVC_TYPE_PING_REQ, ...encodePing(req))
      .pipe(
        take(1),
        map(res => decodePing(res))
      );
  }
}
