import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  ProtocolDecoder,
  ProtocolMessage,
  PacketBodyValue,
  BodyStringDivider,
  ProtocolStream,
  decodeProtocolMessage
} from '@ucap-webmessenger/protocol';
import { DeptType } from '../types/dept.type';
import { DeptInfo } from '../models/dept-info';

export interface DeptRequest extends ProtocolRequest {
  // DivCD(s)
  divCd: string;
  // 기관코드(s)
  companyCode: string;
}

export interface DeptData extends ProtocolStream {
  // DivCD(s)
  divCd: string;
  // {부서정보-S}...
  departmentInfos: DeptInfo[];
}
export interface DeptResponse extends ProtocolResponse {
  // DivCD(s)
  divCd: string;
}

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

  bodyList.push({ type: PacketBodyValue.String, value: req.divCd });
  bodyList.push({ type: PacketBodyValue.String, value: req.companyCode });
  return bodyList;
};

export const decodeDeptData: ProtocolDecoder<DeptData> = (
  message: ProtocolMessage
) => {
  const departmentInfos: DeptInfo[] = [];
  message.bodyList.slice(1).forEach(deptInfo => {
    const info = deptInfo.split(BodyStringDivider);
    departmentInfos.push({
      seq: Number(info[0]),
      name: info[1],
      companyCode: info[2],
      type: info[3] as DeptType,
      rootSeq: Number(info[4]),
      parentSeq: Number(info[5]),
      order: info[6],
      depth: Number(info[7]),
      isActive: info[8] === 'Y' ? true : false,
      nameEn: info[9],
      nameCn: info[10]
    });
  });
  return decodeProtocolMessage(message, {
    divCd: message.bodyList[0],
    departmentInfos
  } as DeptData);
};

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