import { DeviceType } from '@ucap-webmessenger/core';
import {
  APIRequest,
  APIResponse,
  APIEncoder,
  APIDecoder,
  ParameterUtil,
  JsonAnalization,
  StatusCode
} from '@ucap-webmessenger/api';

export interface TranslationSaveRequest extends APIRequest {
  userSeq: number;
  deviceType: DeviceType;
  token: string;
  roomSeq?: string;
  original?: string;
  srcLocale: string;
  destLocale: string;
}

export interface TranslationSaveResponse extends APIResponse {
  translationSeq?: string;
  roomSeq?: string;
  registrationDate?: string;
  srcLocale?: string;
  destLocale?: string;
  original?: string;
  translation?: string;
  returnJson?: any;
}

const translationSaveEncodeMap = {
  userSeq: 'p_user_seq',
  deviceType: 'p_device_type',
  token: 'p_token',
  roomSeq: 'p_room_id',
  original: 'p_original',
  srcLocale: 'p_src_locale',
  destLocale: 'p_dest_locale'
};

export const encodeTranslationSave: APIEncoder<TranslationSaveRequest> = (
  req: TranslationSaveRequest
) => {
  return ParameterUtil.encode(translationSaveEncodeMap, req);
};

export const decodeTranslationSave: APIDecoder<TranslationSaveResponse> = (
  res: any
) => {
  try {
    const json = JsonAnalization.receiveAnalization(res);
    return {
      statusCode: json.StatusCode,
      translationSeq: json.EventTransSEQ,
      roomSeq: json.RoomID,
      registrationDate: json.RegDate,
      srcLocale: json.SrcLocale,
      destLocale: json.DestLocale,
      original: json.Original,
      translation: json.Translation,
      returnJson: res
    } as TranslationSaveResponse;
  } catch (e) {
    return {
      statusCode: StatusCode.Fail,
      errorMessage: e
    } as TranslationSaveResponse;
  }
};
