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

export interface StatusRequest extends ProtocolRequest {
  // 상태타입(s)
  statusDivisionType: StatusType;
  // 상태코드(s)
  statusType: StatusCode;
  // 상태메시지(s) (상태타입 : M, 상태코드: B 일때, 사용함)
  statusMessage?: string;
}

export interface StatusResponse extends ProtocolResponse {
  // 상태타입(s)
  statusDivisionType: StatusType;
  // 상태코드(s)
  statusType: StatusCode;
  // 상태메시지(s) (상태타입 : M, 상태코드: B 일때, 사용함)
  statusMessage: string;
}

export interface StatusNotification extends StatusInfo, ProtocolNotification {}

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

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

export const decodeStatus: ProtocolDecoder<StatusResponse> = (
  message: ProtocolMessage
) => {
  return decodeProtocolMessage(message, {
    statusDivisionType: message.bodyList[0] as StatusType,
    statusType: message.bodyList[1] as StatusCode,
    statusMessage: message.bodyList[2]
  } as StatusResponse);
};

export const decodeStatusNotification: ProtocolDecoder<StatusNotification> = (
  message: ProtocolMessage
) => {
  const info = message.bodyList[0].split(BodyStringDivider);
  return decodeProtocolMessage(message, {
    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,
    workstatus: info[8] as WorkStatusType
  } as StatusNotification);
};
