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

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

import { ProtocolService } from '@ucap-webmessenger/protocol';
import {
  LoginRequest,
  LoginResponse,
  encodeLogin,
  decodeLogin
} from '../models/login';
import {
  SVC_TYPE_LOGIN,
  SSVC_TYPE_LOGIN_REQ,
  SVC_TYPE_LOGOUT,
  SSVC_TYPE_LOGOUT_REQ,
  SSVC_TYPE_LOGOUT_REMOTE_REQ
} from '../types/service';
import {
  LogoutRequest,
  LogoutResponse,
  encodeLogout,
  decodeLogout
} from '../models/logout';
import {
  encodeLogoutRemote,
  decodeLogoutRemote,
  LogoutRemoteRequest,
  LogoutRemoteResponse
} from '../models/logout-remote';

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

  public login(req: LoginRequest): Observable<LoginResponse> {
    return this.protocolService
      .call(SVC_TYPE_LOGIN, SSVC_TYPE_LOGIN_REQ, ...encodeLogin(req))
      .pipe(
        take(1),
        map(res => decodeLogin(res))
      );
  }

  public logout(req: LogoutRequest): Observable<LogoutResponse> {
    return this.protocolService
      .call(SVC_TYPE_LOGOUT, SSVC_TYPE_LOGOUT_REQ, ...encodeLogout(req))
      .pipe(
        take(1),
        map(res => decodeLogout(res))
      );
  }

  public logoutRemote(
    req: LogoutRemoteRequest
  ): Observable<LogoutRemoteResponse> {
    return this.protocolService
      .call(
        SVC_TYPE_LOGOUT,
        SSVC_TYPE_LOGOUT_REMOTE_REQ,
        ...encodeLogoutRemote(req)
      )
      .pipe(
        take(1),
        map(res => decodeLogoutRemote(res))
      );
  }
}
