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?: number;
  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 {
    return {
      statusCode: res.StatusCode,
      translationSeq: !!res.EventTransSeq ? Number(res.EventTransSeq) : 0,
      roomSeq: res.RoomID,
      registrationDate: res.RegDate,
      srcLocale: res.SrcLocale,
      destLocale: res.DestLocale,
      original: res.Original,
      translation: res.Translation,
      returnJson: JSON.stringify(res)
    } as TranslationSaveResponse;
  } catch (e) {
    return {
      statusCode: StatusCode.Fail,
      errorMessage: e
    } as TranslationSaveResponse;
  }
};
