import { DeviceType } from '@ucap-webmessenger/core';
import {
  APIRequest,
  APIResponse,
  APIEncoder,
  APIDecoder,
  ParameterUtil,
  StatusCode,
  JsonAnalization,
  APIFormDataEncoder
} from '@ucap-webmessenger/api';
import { FileUploadItem } from '../../../../ucap-webmessenger-api/src/lib/models/file-upload-item';

export interface FileTalkSaveMultiRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  token: string;
  files: File[];
  fileUploadItems: FileUploadItem;
  roomSeq?: string;
}

export interface FileTalkSaveMultiResponse extends APIResponse {
  roomSeq?: string;
  attachmentSeq?: string;
  fileCount?: string;
  baseUrl?: string;
  fileType?: string;
  thumbnailUrls?: string[];
  returnJson?: string;
}

const fileTalkSaveEncodeMapTemp = {
  userSeq: 'p_user_seq',
  deviceType: 'p_device_type',
  token: 'p_token',
  roomSeq: 'p_room_id',
  files: 'file',
  type: 'p_type'
};

export const encodeFileTalkSaveMulti: APIFormDataEncoder<FileTalkSaveMultiRequest> = (
  req: FileTalkSaveMultiRequest
) => {
  const extraParams: any = {};
  extraParams.userSeq = String(req.userSeq);

  return ParameterUtil.encodeFormData(
    fileTalkSaveEncodeMapTemp,
    req,
    extraParams
  );
};

export const decodeFileTalkSaveMulti: APIDecoder<FileTalkSaveMultiResponse> = (
  res: any
) => {
  try {
    const json = JsonAnalization.receiveAnalization(res);
    const fileTypeDefault =
      !json.fileType || json.fileType === '' ? 'b' : json.fileType;
    return {
      statusCode: json.StatusCode,
      roomSeq: json.RoomID,
      attachmentSeq: json.AttSEQ,
      fileCount: json.FileCount,
      fileType: fileTypeDefault,
      baseUrl: json.BaseURL,
      thumbnailUrls: json.ThumbURL,
      returnJson: res
    } as FileTalkSaveMultiResponse;
  } catch (e) {
    return {
      statusCode: StatusCode.Fail,
      errorMessage: e
    } as FileTalkSaveMultiResponse;
  }
};
