import { DeviceType, LocaleCode } from '@ucap-webmessenger/core';
import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage
} from '@ucap-webmessenger/protocol';

export interface GroupUpdateRequest extends ProtocolRequest {
  // 0: 동료그룹SEQ(n)
  groupSeq: number;
  // 1: 동료그룹이름(s)
  groupName: string;
  // 2n: 사용자SEQ(n)...
  userSeqs: number[];
}

export interface GroupUpdateResponse extends ProtocolResponse {
  // 0: 동료그룹SEQ(n)
  groupSeq: number;
  // 1: 동료그룹이름(s)
  groupName: string;
  // 2n: 사용자SEQ(n)...
  userSeqs: number[];
}

export const encodeGroupUpdate: ProtocolEncoder<GroupUpdateRequest> = (
  req: GroupUpdateRequest
) => {
  const bodyList: PacketBody[] = [];

  bodyList.push(
    { type: PacketBodyValue.Integer, value: req.groupSeq },
    { type: PacketBodyValue.String, value: req.groupName },
    { type: PacketBodyValue.String, value: req.userSeqs.join(',') }
  );

  return bodyList;
};

export const decodeGroupUpdate: ProtocolDecoder<GroupUpdateResponse> = (
  message: ProtocolMessage
) => {
  let userSeqArray: number[] = [];
  if (message.bodyList.length > 2 && !message.bodyList[2].empty()) {
    userSeqArray = message.bodyList[2].split(',').map((v: any) => Number(v));
  }

  return {
    groupSeq: message.bodyList[0],
    groupName: message.bodyList[1],
    userSeqs: userSeqArray
  } as GroupUpdateResponse;
};

export const encodeGroupUpdate2: ProtocolEncoder<GroupUpdateRequest> = (
  req: GroupUpdateRequest
) => {
  const bodyList: PacketBody[] = [];

  bodyList.push(
    { type: PacketBodyValue.Integer, value: req.groupSeq },
    { type: PacketBodyValue.String, value: req.groupName }
  );

  if (req.userSeqs.length > 0) {
    req.userSeqs.forEach(userSeq => {
      bodyList.push({ type: PacketBodyValue.Integer, value: userSeq });
    });
  }

  return bodyList;
};

export const decodeGroupUpdate2: ProtocolDecoder<GroupUpdateResponse> = (
  message: ProtocolMessage
) => {
  let userSeqArray: number[] = [];
  if (message.bodyList.length > 2) {
    userSeqArray = message.bodyList.slice(2);
  }

  return {
    groupSeq: message.bodyList[0],
    groupName: message.bodyList[1],
    userSeqs: userSeqArray
  } as GroupUpdateResponse;
};
