import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  BodyStringDivider,
  ProtocolStream,
  decodeProtocolMessage
} from '@ucap-webmessenger/protocol';
import { GroupInfo } from '../models/group-info';

export interface GroupRequest extends ProtocolRequest {
  // 0. 동료 씽크일시(s) cf)2019-09-24 16:51:42
  syncDate: string;
}

export interface GroupData extends ProtocolStream {
  // n. {동료그룹정보}...
  groupInfos: GroupInfo[];
}

export interface GroupDetailData extends ProtocolStream {
  // 그룹SEQ(n)
  seq: number;
  // 그룹이름(s)
  name: string;
  // ActiveYN(s)
  isActive: boolean;
  // 사용자SEQ(n)1
  userSeqs: number[];
}

export interface GroupResponse extends ProtocolResponse {
  // 0. 동료 씽크일시(s) cf)2019-09-24 16:51:42
  syncDate: string;
}

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

  bodyList.push({ type: PacketBodyValue.String, value: req.syncDate || ' ' });
  return bodyList;
};

export const decodeGroup: ProtocolDecoder<GroupResponse> = (
  message: ProtocolMessage
) => {
  return decodeProtocolMessage(message, {
    syncDate: message.bodyList[0]
  } as GroupResponse);
};

export const decodeGroupData: ProtocolDecoder<GroupData> = (
  message: ProtocolMessage
) => {
  const groupInfos: GroupInfo[] = [];
  message.bodyList.forEach(buddyinfo => {
    const info = buddyinfo.split(BodyStringDivider);
    groupInfos.push({
      seq: Number(info[0]),
      name: info[1],
      isActive: info[2] === 'Y' ? true : false,
      userSeqStr: info[3]
    });
  });

  return decodeProtocolMessage(message, {
    groupInfos
  } as GroupData);
};

export const decodeGroupDetailData: ProtocolDecoder<GroupDetailData> = (
  message: ProtocolMessage
) => {
  const userSeqs: number[] = [];
  if (message.bodyList.length > 3) {
    message.bodyList.slice(3).forEach(seq => {
      if (seq !== 0) {
        userSeqs.push(seq);
      }
    });
  }
  return decodeProtocolMessage(message, {
    // 그룹SEQ(n)
    seq: message.bodyList[0],
    // 그룹이름(s)
    name: message.bodyList[1],
    // ActiveYN(s)
    isActive: message.bodyList[2] === 'Y' ? true : false,
    // 사용자SEQ(n)1
    userSeqs
  } as GroupDetailData);
};
