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

export interface DataUserRequest extends ProtocolRequest {
  // DivCD(s)
  divCd: string;
  // 사용자SEQ(n)
  seq: number;
  // 발신자회사코드(s)
  senderCompanyCode: string;
  // 발신자임직원유형(s)
  senderEmployeeType: EmployeeType;
}
export interface DataUserResponse extends ProtocolResponse {
  // DivCD(s)
  divCd: string;
  // {사용자정보-SS}
  userInfo?: UserInfoSS;
}

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

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

  return bodyList;
};

export const decodeDataUser: ProtocolDecoder<DataUserResponse> = (
  message: ProtocolMessage
) => {
  let userInfo: UserInfoSS;
  if (message.bodyList.length > 1) {
    const info = message.bodyList[1].split(BodyStringDivider);
    userInfo = {
      seq: Number(info[0]),
      name: info[1],
      profileImageFile: info[2],
      grade: info[3],
      intro: info[4],
      companyCode: info[5],
      hpNumber: info[6],
      lineNumber: info[7],
      email: info[8],
      isMobile: info[9] === 'Y' ? true : false,
      deptName: info[10],
      order: info[11],
      isActive: info[12] === 'Y' ? true : false,
      roleCd: info[13] as RoleCode,
      employeeNum: info[14],
      madn: info[15],
      hardSadn: info[16],
      fmcSadn: info[17],
      callMode: info[18],
      nameEn: info[19],
      nameCn: info[20],
      gradeEn: info[21],
      gradeCn: info[22],
      deptNameEn: info[23],
      deptNameCn: info[24],
      deptSeq: info[25],
      isPrivacyAgree: info[26] === 'Y' ? true : false,
      isValidLogin: info[27] === 'Y' ? true : false,
      employeeType: info[28] as EmployeeType
    };
  }
  return decodeProtocolMessage(message, {
    divCd: message.bodyList[0],
    userInfo
  } as DataUserResponse);
};
