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 FileTalkSaveRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  token: string;
  file: File;
  fileName?: string;
  fileUploadItem: FileUploadItem;
  thumb?: File;
  voice?: boolean;
  voiceTime?: string;
  roomSeq?: string;
  type?: string;
}

export interface FileTalkSaveResponse extends APIResponse {
  roomSeq?: string;
  fileName?: string;
  fileExt?: string;
  fileType?: string;
  thumbnailUrl?: string;
  attachmentSeq?: string;
  attachmentSize?: string;
  attachmentRegDate?: string;
  imageWidth?: string;
  imageHeight?: string;
  companyCode?: string;
  voiceTime?: string;
  synapKey?: string;
  returnJson?: any;
}

const fileTalkSaveEncodeMap = {
  userSeq: 'p_user_seq',
  deviceType: 'p_device_type',
  token: 'p_token',
  file: 'file',
  fileName: 'p_file_name',
  thumb: 'thumb',
  voice: 'p_voice',
  voiceTime: 'p_voice_time',
  roomSeq: 'p_room_id',
  type: 'p_type'
};

export const encodeFileTalkSave: APIFormDataEncoder<FileTalkSaveRequest> = (
  req: FileTalkSaveRequest
) => {
  const extraParams: any = {};

  extraParams.userSeq = String(req.userSeq);
  if (!!req.voice) {
    extraParams.voice = req.voice ? 'Y' : 'N';
  }

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

export const decodeFileTalkSave: APIDecoder<FileTalkSaveResponse> = (
  res: any
) => {
  try {
    const json = JsonAnalization.receiveAnalization(res);
    return {
      statusCode: json.StatusCode,
      roomSeq: json.RoomID,
      fileName: json.FileName,
      fileExt: json.FileExt,
      fileType: json.FileType,
      thumbnailUrl: json.ThumbURL,
      attachmentSeq: json.AttSEQ,
      attachmentSize: json.AttSize,
      attachmentRegDate: json.AttRegDate,
      imageWidth: json.ImageWidth,
      imageHeight: json.ImageHeight,
      companyCode: json.CompanyCode,
      voiceTime: json.VoiceTime,
      synapKey: json.SynapKey,
      returnJson: res
    } as FileTalkSaveResponse;
  } catch (e) {
    return {
      statusCode: StatusCode.Fail,
      errorMessage: e
    } as FileTalkSaveResponse;
  }
};
