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

export interface SubscribeRequest extends ProtocolRequest {
  // 사용자SEQ(n)...
  userSeqs: number[];
}

export interface SubscribeResponse extends ProtocolResponse {
  // {상태정보}...
  statusInfos: StatusInfo[];
}

/**
 * @deprecated not support server
 */
export interface SubscribeData extends ProtocolStream {
  // {상태정보}...
  statusInfos: StatusInfo[];
}

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

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

export const decodeSubscribe: ProtocolDecoder<SubscribeResponse> = (
  message: ProtocolMessage
) => {
  const statusInfos: StatusInfo[] = [];
  message.bodyList.forEach(statusInfo => {
    const info = statusInfo.split(BodyStringDivider);
    statusInfos.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
    });
  });
  return decodeProtocolMessage(message, {
    statusInfos
  } as SubscribeResponse);
};

/**
 * @deprecated not support server
 */
// tslint:disable-next-line: deprecation
export const decodeSubscribeData: ProtocolDecoder<SubscribeData> = (
  message: ProtocolMessage
) => {
  const statusInfos: StatusInfo[] = [];
  message.bodyList.forEach(statusInfo => {
    const info = statusInfo.split(BodyStringDivider);
    statusInfos.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
    });
  });
  return decodeProtocolMessage(message, {
    statusInfos
    // tslint:disable-next-line: deprecation
  } as SubscribeData);
};
