import {
  APIRequest,
  MessageAPIResponse,
  APIJsonEncoder,
  APIDecoder,
  APIFormDataEncoder,
  ParameterUtil,
  MessageStatusCode
} from '@ucap-webmessenger/api';
import { DeviceType } from '@ucap-webmessenger/core';
import { MessageType } from '../types/message.type';
import { CategoryType } from '../types/category.type';
import { ContentType } from '../types/content.type';
import { FileUploadItem } from '@ucap-webmessenger/api';

export interface SendRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  tokenKey: string;
  type: MessageType;

  userName: string;
  category: CategoryType;
  title: string;
  titleYn: boolean;
  listOrder: ContentType[];
  reservationTime?: string;
  smsYn?: boolean;

  textContent: { text: string }[];
  recvUserList: { userSeq: number; userName: string }[];

  files?: File[];
  fileUploadItem?: FileUploadItem;
}

export interface SendResponse extends MessageAPIResponse {}

const sendEncodeMap = {
  userSeq: 'userSeq',
  deviceType: 'deviceType',
  tokenKey: 'tokenKey',
  type: 'type',
  userName: 'userName',
  category: 'category',
  title: 'title',
  titleYn: 'titleYn',
  listOrder: 'listOrder',
  reservationTime: 'reservationTime',
  smsYn: 'smsYn',
  textContent: 'textContent',
  recvUserList: 'recvUserList',
  files: 'files'
};

export const encodeSend: APIFormDataEncoder<SendRequest> = (
  req: SendRequest
) => {
  const extraParams: any = {};

  extraParams.userSeq = String(req.userSeq);
  if (!!req.titleYn) {
    extraParams.titleYn = req.titleYn ? 'Y' : 'N';
  }
  if (!!req.smsYn) {
    extraParams.smsYn = req.smsYn ? 'Y' : 'N';
  }
  if (!!req.listOrder) {
    let s = '';
    req.listOrder.forEach(v => {
      s = s + String(v);
    });
    extraParams.listOrder = s;
  }
  if (!!req.textContent) {
    extraParams.textContent = JSON.stringify(req.textContent);
  }
  if (!!req.recvUserList) {
    extraParams.recvUserList = JSON.stringify(req.recvUserList);
  }
  return ParameterUtil.encodeFormData(sendEncodeMap, req, extraParams);
};

export const decodeSend: APIDecoder<SendResponse> = (res: any) => {
  return {
    responseCode: res.responseCode as MessageStatusCode,
    responseMsg: res.responseMsg
  } as SendResponse;
};
