import { StatusCode } from '@ucap-webmessenger/core';
import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  BodyStringDivider,
  decodeProtocolMessage
} from '@ucap-webmessenger/protocol';
import { StatusInfo } from '@ucap-webmessenger/protocol-status';

export interface StatusRequest extends ProtocolRequest {
  // 사용자SEQ(n)...
  userSeqs: number[];
}

export interface StatusResponse extends ProtocolResponse {
  // {상태정보}...
  statusInfos: StatusInfo[];
}

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

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

export const decodeStatus: ProtocolDecoder<StatusResponse> = (
  message: ProtocolMessage
) => {
  const statusInfos: StatusInfo[] = [];
  message.bodyList.forEach(statusInfo => {
    const info = statusInfo.split(BodyStringDivider);
    statusInfos.push({
      userSeq: Number(info[0]),
      pcStatus: info[1] as StatusCode,
      phoneStatus: info[2] as StatusCode,
      mobileStatus: info[3] as StatusCode,
      conferenceStatus: info[4] as StatusCode,
      statusMessage: info[5],
      mobileConferenceStatus: info[6] as StatusCode,
      imessengerStatus: info[7] as StatusCode
    });
  });
  return decodeProtocolMessage(message, {
    statusInfos
  } as StatusResponse);
};
