import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  ProtocolDecoder,
  ProtocolMessage,
  PacketBodyValue,
  BodyStringDivider,
  ProtocolStream,
  decodeProtocolMessage
} from '@ucap-webmessenger/protocol';
import { EmployeeType } from '@ucap-webmessenger/protocol-room';
import { UserSeqInfo } from '../models/user-seq-info';

export interface UserIdRequest extends ProtocolRequest {
  // DivCD(s)
  divCd: string;
  // 사용자SEQs(s)
  loginSeqs: number[];
  // 발신자회사코드(s)
  senderCompanyCode: string;
  // 발신자임직원유형(s)
  senderEmployeeType: EmployeeType;
}

export interface UserIdData extends ProtocolStream {
  // DivCD(s)
  divCd: string;
  // {SEQ정보}1...
  userSeqInfos: UserSeqInfo[];
}

export interface UserIdResponse extends ProtocolResponse {
  // DivCD(s)
  divCd: string;
}

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

  bodyList.push(
    { type: PacketBodyValue.String, value: req.divCd },
    { type: PacketBodyValue.Integer, value: req.loginSeqs.join(',') },
    { type: PacketBodyValue.String, value: req.senderCompanyCode },
    { type: PacketBodyValue.String, value: req.senderEmployeeType }
  );

  return bodyList;
};

export const decodeUserIdData: ProtocolDecoder<UserIdData> = (
  message: ProtocolMessage
) => {
  const userSeqInfos: UserSeqInfo[] = [];
  message.bodyList.slice(1).forEach(userInfo => {
    const info = userInfo.split(BodyStringDivider);
    userSeqInfos.push({
      id: info[0],
      seq: Number(info[1]),
      isMobile: info[2] === 'Y' ? true : false,
      companyCode: info[3]
    });
  });
  return decodeProtocolMessage(message, {
    divCd: message.bodyList[0],
    userSeqInfos
  } as UserIdData);
};

export const decodeUserId: ProtocolDecoder<UserIdResponse> = (
  message: ProtocolMessage
) => {
  return decodeProtocolMessage(message, { divCd: message.bodyList[0] } as UserIdResponse);
};
