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

export interface EditReservationRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  tokenKey: string;
  msgId: number;
  category: CategoryType;
  title: string;
  titleYn: boolean;
  listOrder: ContentType[];
  resSeqList: number[];
  reservationTime: string;
  smsYn?: boolean;

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

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

export interface EditReservationResponse extends MessageAPIResponse {}

const editReservationEncodeMap = {
  userSeq: 'userSeq',
  deviceType: 'deviceType',
  tokenKey: 'tokenKey',
  msgId: 'msgId',
  category: 'category',
  title: 'title',
  titleYn: 'titleYn',
  listOrder: 'listOrder',
  resSeqList: 'resSeqList',
  reservationTime: 'reservationTime',
  smsYn: 'smsYn',
  textContent: 'textContent',
  recvUserList: 'recvUserList',
  files: 'files'
};

export const encodeEditReservation: APIFormDataEncoder<EditReservationRequest> = (
  req: EditReservationRequest
) => {
  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.resSeqList) {
    extraParams.resSeqList = req.resSeqList.map(v => v.toString()).join(',');
  }
  if (!!req.textContent) {
    extraParams.textContent = JSON.stringify(req.textContent);
  }
  if (!!req.recvUserList) {
    extraParams.recvUserList = JSON.stringify(req.recvUserList);
  }
  return ParameterUtil.encodeFormData(
    editReservationEncodeMap,
    req,
    extraParams
  );
};

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