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

export interface FileProfileSaveRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  token: string;
  file?: File;
  fileUploadItem: FileUploadItem;
  intro?: string;
  initProfileImage?: boolean;
}

export interface FileProfileSaveResponse extends APIResponse {
  profileURL?: string;
  profileSubDir?: string;
  returnJson?: any;
}

const fileProfileEncodeMap = {
  userSeq: 'p_user_seq',
  deviceType: 'p_device_type',
  token: 'p_token',
  file: 'file',
  intro: 'p_intro',
  initProfileImage: 'p_init_profile_img_yn'
};

export const encodeFileProfileSave: APIFormDataEncoder<FileProfileSaveRequest> = (
  req: FileProfileSaveRequest
) => {
  const extraParams: any = {};

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

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

export const decodeFileProfileSave: APIDecoder<FileProfileSaveResponse> = (
  res: any
) => {
  try {
    const json = JsonAnalization.receiveAnalization(res);
    return {
      statusCode: json.StatusCode,
      profileURL: json.ProfileURL,
      profileSubDir: json.ProfileSubDir,
      returnJson: res
    } as FileProfileSaveResponse;
  } catch (e) {
    return {
      statusCode: StatusCode.Fail,
      errorMessage: e
    } as FileProfileSaveResponse;
  }
};
