import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  BodyStringDivider,
  ProtocolStream,
  decodeProtocolMessage
} from '@ucap-webmessenger/protocol';
import { StatusCode } from '@ucap-webmessenger/core';
import {
  TerminalStatusInfo,
  TerminalStatusNumber
} from '../types/terminal-status.type';
import { StatusInfo } from '../models/status-info';
import { StatusBulkInfo } from '../models/status-bulk-info';
import { WorkStatusType } from '../types/work-status.type';

export interface BulkInfoRequest extends ProtocolRequest {
  /** DivCD(s) */
  divCd: string;
  /** 사용자SEQ(n)[] */
  userSeqs: number[];
}

export interface BulkInfoData extends ProtocolStream {
  /** DivCD(s) */
  divCd: string;
  /** {상태정보Bulk}... */
  statusBulkInfos: StatusBulkInfo[];
}
export interface BulkInfoResponse extends ProtocolResponse {
  /** DivCD(s) */
  divCd: string;
}

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

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

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

export const decodeBulkInfoData: ProtocolDecoder<BulkInfoData> = (
  message: ProtocolMessage
) => {
  const statusBulkInfos: StatusBulkInfo[] = [];
  message.bodyList.slice(1).forEach(statusBulkInfo => {
    const info = statusBulkInfo.split(BodyStringDivider);
    statusBulkInfos.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,
      terminalStatus: info[8] as TerminalStatusInfo,
      terminalStatusNumber: Number(info[9]) as TerminalStatusNumber,
      workstatus: info[10] as WorkStatusType
    });
  });
  return decodeProtocolMessage(message, {
    divCd: message.bodyList[0],
    statusBulkInfos
  } as BulkInfoData);
};
