import { DeviceType, LocaleCode } from '@ucap-webmessenger/core';
import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  decodeProtocolMessage,
  ProtocolNotification
} from '@ucap-webmessenger/protocol';

export interface UpdateRequest extends ProtocolRequest {
  /** 0: 동료그룹SEQ(n) */
  groupSeq: number;
  /** 1: 동료그룹이름(s) */
  groupName: string;
  /** 2n: 사용자SEQ(n)... */
  userSeqs: number[];
}

export interface UpdateResponse extends ProtocolResponse {
  /** 0: 동료그룹SEQ(n) */
  groupSeq: number;
  /** 1: 동료그룹이름(s) */
  groupName: string;
  /** 2n: 사용자SEQ(n)... */
  userSeqs: number[];
}

export interface UpdateNotification extends ProtocolNotification {
  /** 0: 동료그룹SEQ(n) */
  groupSeq: number;
  /** 1: 동료그룹이름(s) */
  groupName: string;
  /** 2n: 사용자SEQ(n)... */
  userSeqs: number[];
}

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

  bodyList.push(
    { type: PacketBodyValue.Integer, value: req.groupSeq },
    { type: PacketBodyValue.String, value: req.groupName },
    { type: PacketBodyValue.String, value: req.userSeqs.join(',') }
  );

  return bodyList;
};

export const decodeUpdate: ProtocolDecoder<UpdateResponse> = (
  message: ProtocolMessage
) => {
  let userSeqArray: number[] = [];
  if (message.bodyList.length > 2 && !message.bodyList[2].empty()) {
    userSeqArray = message.bodyList[2].split(',').map((v: any) => Number(v));
  }

  return decodeProtocolMessage(message, {
    groupSeq: message.bodyList[0],
    groupName: message.bodyList[1],
    userSeqs: userSeqArray
  } as UpdateResponse);
};

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

  bodyList.push(
    { type: PacketBodyValue.Integer, value: req.groupSeq },
    { type: PacketBodyValue.String, value: req.groupName }
  );

  if (req.userSeqs.length > 0) {
    req.userSeqs.forEach(userSeq => {
      bodyList.push({ type: PacketBodyValue.Integer, value: userSeq });
    });
  }

  return bodyList;
};

export const decodeUpdate2: ProtocolDecoder<UpdateResponse> = (
  message: ProtocolMessage
) => {
  let userSeqArray: number[] = [];
  if (message.bodyList.length > 2) {
    userSeqArray = message.bodyList.slice(2);
  }

  return decodeProtocolMessage(message, {
    groupSeq: message.bodyList[0],
    groupName: message.bodyList[1],
    userSeqs: userSeqArray
  } as UpdateResponse);
};

export const decodeUpdate2Notification: ProtocolDecoder<UpdateNotification> = (
  message: ProtocolMessage
) => {
  let userSeqArray: number[] = [];
  if (message.bodyList.length > 2) {
    userSeqArray = message.bodyList.slice(2);
  }

  return decodeProtocolMessage(message, {
    groupSeq: message.bodyList[0],
    groupName: message.bodyList[1],
    userSeqs: userSeqArray
  } as UpdateNotification);
};
