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

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

import { ProtocolService } from '@ucap-webmessenger/protocol';
import {
  GroupAddRequest,
  encodeGroupAdd,
  decodeGroupAdd,
  GroupAddResponse
} from '../models/add';
import {
  SVC_TYPE_GROUP,
  SSVC_TYPE_GROUP_ADD_REQ,
  SSVC_TYPE_GROUP_DEL_REQ,
  SSVC_TYPE_GROUP_UPD_REQ,
  SSVC_TYPE_GROUP_UPD_REQ2
} from '../types/service';
import {
  GroupDelRequest,
  encodeGroupDel,
  decodeGroupDel,
  GroupDelResponse
} from '../models/del';
import {
  GroupUpdateRequest,
  encodeGroupUpdate,
  decodeGroupUpdate,
  encodeGroupUpdate2,
  decodeGroupUpdate2,
  GroupUpdateResponse
} from '../models/update';
@Injectable({
  providedIn: 'root'
})
export class GroupProtocolService {
  constructor(private protocolService: ProtocolService) {}

  public groupAdd(req: GroupAddRequest): Observable<GroupAddResponse> {
    return this.protocolService
      .call(SVC_TYPE_GROUP, SSVC_TYPE_GROUP_ADD_REQ, ...encodeGroupAdd(req))
      .pipe(
        take(1),
        map(res => decodeGroupAdd(res))
      );
  }

  public groupDel(req: GroupDelRequest): Observable<GroupDelResponse> {
    return this.protocolService
      .call(SVC_TYPE_GROUP, SSVC_TYPE_GROUP_DEL_REQ, ...encodeGroupDel(req))
      .pipe(
        take(1),
        map(res => decodeGroupDel(res))
      );
  }

  public groupUpdate(req: GroupUpdateRequest): Observable<GroupUpdateResponse> {
    return this.protocolService
      .call(SVC_TYPE_GROUP, SSVC_TYPE_GROUP_UPD_REQ, ...encodeGroupUpdate(req))
      .pipe(
        take(1),
        map(res => decodeGroupUpdate(res))
      );
  }

  public groupUpdate2(
    req: GroupUpdateRequest
  ): Observable<GroupUpdateResponse> {
    return this.protocolService
      .call(
        SVC_TYPE_GROUP,
        SSVC_TYPE_GROUP_UPD_REQ2,
        ...encodeGroupUpdate2(req)
      )
      .pipe(
        take(1),
        map(res => decodeGroupUpdate2(res))
      );
  }
}
