import { Injectable } from '@angular/core';
import { ProtocolService } from '@ucap-webmessenger/protocol';
import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';
import {
  AuthRequest,
  AuthResponse,
  encodeAuth,
  decodeAuth
} from '../models/auth';
import {
  SVC_TYPE_QUERY_DATA,
  SSVC_TYPE_QUERY_AUTH_REQ
} from '../types/service';

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

  public auth(req: AuthRequest): Observable<AuthResponse> {
    return this.protocolService
      .call(SVC_TYPE_QUERY_DATA, SSVC_TYPE_QUERY_AUTH_REQ, ...encodeAuth(req))
      .pipe(
        take(1),
        map(res => decodeAuth(res))
      );
  }
}
