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

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

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

import {
  SVC_TYPE_BUDDY,
  SSVC_TYPE_BUDDY_ADD_REQ,
  SSVC_TYPE_BUDDY_DEL_REQ,
  SSVC_TYPE_BUDDY_UPD_REQ
} from '../types/service';

import {
  BuddyAddRequest,
  encodeBuddyAdd,
  decodeBuddyAdd,
  BuddyAddResponse
} from '../models/add';
import {
  BuddyDelRequest,
  encodeBuddyDel,
  decodeBuddyDel,
  BuddyDelResponse
} from '../models/del';
import {
  BuddyUpdateRequest,
  decodeBuddyUpdate,
  encodeBuddyUpdate,
  BuddyUpdateResponse
} from '../models/update';

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

  public buddyAdd(req: BuddyAddRequest): Observable<BuddyAddResponse> {
    return this.protocolService
      .call(SVC_TYPE_BUDDY, SSVC_TYPE_BUDDY_ADD_REQ, ...encodeBuddyAdd(req))
      .pipe(
        take(1),
        map(res => decodeBuddyAdd(res))
      );
  }

  public buddyDel(req: BuddyDelRequest): Observable<BuddyDelResponse> {
    return this.protocolService
      .call(SVC_TYPE_BUDDY, SSVC_TYPE_BUDDY_DEL_REQ, ...encodeBuddyDel(req))
      .pipe(
        take(1),
        map(res => decodeBuddyDel(res))
      );
  }

  public buddyUpdate(req: BuddyUpdateRequest): Observable<BuddyUpdateResponse> {
    return this.protocolService
      .call(SVC_TYPE_BUDDY, SSVC_TYPE_BUDDY_UPD_REQ, ...encodeBuddyUpdate(req))
      .pipe(
        take(1),
        map(res => decodeBuddyUpdate(res))
      );
  }
}
