import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  BodyStringDivider
} from '@ucap-webmessenger/protocol';
import { LocaleCode } from '@ucap-webmessenger/core';
import { RoomType } from '../types/room.type';
import { EventType } from '@ucap-webmessenger/protocol-event';
import { EmployeeType } from '../types/employee.type';
import { RoleCode } from '@ucap-webmessenger/protocol-authentication';

export interface RoomInfo {
  // 0. 대화방SEQ
  roomSeq: string;
  // 1. 대화방종류
  roomType: RoomType;
  // 2. 대화방명
  roomName: string;
  // 3. 최종타입
  finalEventType: EventType;
  // 4. 최종대화
  finalEventMessage: string;
  // 5. 최종시간
  finalEventDate: string;
  // 6. 참여인원수
  joinUserCount: number;
  // 7. 안읽은수
  noReadCnt: number;
  // 8. 알람여부
  isAlarm: boolean;
  // 9. 참여여부
  isJoinRoom: boolean;
  // 10. 유효한파일 이벤트 기준 SEQ
  expiredFileStdSeq: number;
  // 11. 타이머대화방여부YN
  isTimeRoom: boolean;
  // 12. 타이머시간(n)
  timeRoomInterval: number;
}

export interface UserInfoShort {
  // 0. 사용자SEQ
  seq: number;
  // 1. 사용자명
  name: string;
  // 2. 사진파일
  profileImageFile: string;
  // 3. 참여여부
  isJoinRoom: boolean;
  // 4. 최종확인SEQ
  lastReadEventSeq: number;
  // 5. MADN
  madn: string;
  // 6. HARDPHONE_SADN
  hardSadn: string;
  // 7. FMC_SADN
  fmcSadn: string;
  // 8. 사용자명(영어)
  nameEn: string;
  // 9. 사용자명(중국어)
  nameCn: string;
  // 10. 이용약관동의여부YN
  isPrivacyAgree: boolean;
  // 11. 유효접속여부YN
  isValidLogin: boolean;
  // 12. 임직원유형(s)
  employeeType: EmployeeType;
  // 13. 폰트색(s)
  fontColor: string;
}

export interface UserInfo {
  // 0. 사용자SEQ
  seq: number;
  // 1. 사용자명
  name: string;
  // 2. 사진파일
  profileImageFile: string;
  // 3. 직급
  grade: string;
  // 4. 업무소개
  intro: string;
  // 5. 기관코드
  companyCode: string;
  // 6. 핸드폰번호
  hpNumber: string;
  // 7. 내선번호
  lineNumber: string;
  // 8. 이메일
  email: string;
  // 9. 모바일YN
  isMobile: boolean;
  // 10. 부서명
  deptName: string;
  // 11. 참여 여부 <<<<
  isJoinRoom: boolean;
  // 12. 최종확인SEQ <<<<
  lastReadEventSeq: number;
  // 13. ActiveYN
  isActive: boolean;
  // 14. 역할코드
  roleCd: RoleCode;
  // 15. 사번
  employeeNum: string;
  // 16. MADN
  madn: string;
  // 17. HARDPHONE_SADN
  hardSadn: string;
  // 18. FMC_SADN
  fmcSadn: string;
  // 19. 사용자명(영어)
  nameEn: string;
  // 20. 사용자명(중국어)
  nameCn: string;
  // 21. 직급(영어)
  gradeEn: string;
  // 22. 직급(중국어)
  gradeCn: string;
  // 23. 부서명(영어)
  deptNameEn: string;
  // 24. 부서명(중국어)
  deptNameCn: string;
  // 25. CALL_MODE <<<
  callMode: string;
  // 26. 이용약관동의여부YN
  isPrivacyAgree: boolean;
  // 27. 유효접속여부YN
  isValidLogin: boolean;
  // 28. 임직원유형(s)
  employeeType: EmployeeType;
  // 29. 사용자아이디(s) <<<
  id: string;
}

export interface RoomInfoRequest extends ProtocolRequest {
  // 0. 대화방SEQ(s)
  roomSeq: string;
  // 1. 상세정보여부(y)
  isDetail: boolean;
  // 2. 언어코드(s)
  localeCode: LocaleCode;
}

export interface RoomInfoResponse extends ProtocolResponse {
  // 0. 대화방SEQ(s)
  roomSeq: string;
}

export interface RoomInfoDataResponse extends ProtocolResponse {
  // 0. 대화방SEQ(s)
  roomSeq: string;
  // 1. {대화방정보}
  roomInfo: RoomInfo;
}

export interface RoomUserShortDataResponse extends ProtocolResponse {
  // 0. 대화방SEQ(s)
  roomSeq: string;
  // 1n. {참여자정보}
  userInfos: UserInfoShort[];
}
export interface RoomUserDataResponse extends ProtocolResponse {
  // 0. 대화방SEQ(s)
  roomSeq: string;
  // 1n. {참여자정보-D}
  userInfos: UserInfo[];
}

export const encodeRoomInfo: ProtocolEncoder<RoomInfoRequest> = (
  req: RoomInfoRequest
) => {
  const bodyList: PacketBody[] = [];

  bodyList.push({ type: PacketBodyValue.String, value: req.roomSeq });
  bodyList.push({
    type: PacketBodyValue.String,
    value: req.isDetail !== true ? 'N' : 'Y'
  }); // 요청응답을 상세로 받는것을 default
  bodyList.push({ type: PacketBodyValue.String, value: req.localeCode });

  return bodyList;
};

export const decodeRoomInfo: ProtocolDecoder<RoomInfoResponse> = (
  message: ProtocolMessage
) => {
  return {
    roomSeq: message.bodyList[0]
  } as RoomInfoResponse;
};

export const decodeRoomInfoData: ProtocolDecoder<RoomInfoDataResponse> = (
  message: ProtocolMessage
) => {
  let roomInfo: RoomInfo = null;
  if (message.bodyList.length > 1) {
    const info = message.bodyList[1].split(BodyStringDivider);
    if (info.length > 11) {
      roomInfo = {
        roomSeq: info[0],
        roomType: info[1] as RoomType,
        roomName: info[2],
        finalEventType: info[3] as EventType,
        finalEventMessage: info[4],
        finalEventDate: info[5],
        joinUserCount: info[6],
        noReadCnt: info[7],
        isAlarm: info[8] !== 'N' ? true : false,
        isJoinRoom: info[9] === 'Y' ? true : false,
        expiredFileStdSeq: info[10],
        isTimeRoom: info[11] === 'Y' ? true : false,
        timeRoomInterval: info[11] !== 'Y' ? 0 : info[12] || 0
      };
    }
  }

  return {
    roomSeq: message.bodyList[0],
    roomInfo
  } as RoomInfoDataResponse;
};

export const decodeRoomUserShortData: ProtocolDecoder<
  RoomUserShortDataResponse
> = (message: ProtocolMessage) => {
  const userInfos: UserInfoShort[] = [];
  message.bodyList.slice(1).forEach(userInfo => {
    const info = userInfo.split(BodyStringDivider);
    userInfos.push({
      seq: info[0],
      name: info[1],
      profileImageFile: info[2],
      isJoinRoom: info[3],
      lastReadEventSeq: info[4],
      madn: info[5],
      hardSadn: info[6],
      fmcSadn: info[7],
      nameEn: info[8],
      nameCn: info[9],
      isPrivacyAgree: info[10] === 'Y' ? true : false,
      isValidLogin: info[11] === 'Y' ? true : false,
      employeeType: info[12] as EmployeeType,
      fontColor: info[13]
    });
  });

  return {
    roomSeq: message.bodyList[0],
    userInfos
  } as RoomUserShortDataResponse;
};

export const decodeRoomUserData: ProtocolDecoder<RoomUserDataResponse> = (
  message: ProtocolMessage
) => {
  const userInfos: UserInfo[] = [];
  message.bodyList.slice(1).forEach(userInfo => {
    const info = userInfo.split(BodyStringDivider);
    userInfos.push({
      seq: info[0],
      name: info[1],
      profileImageFile: info[2],
      grade: info[3],
      intro: info[4],
      companyCode: info[5],
      hpNumber: info[6],
      lineNumber: info[7],
      email: info[8],
      isMobile: info[9] === 'Y' ? true : false,
      deptName: info[10],
      isJoinRoom: info[11] === 'Y' ? true : false,
      lastReadEventSeq: info[12],
      isActive: info[13] === 'Y' ? true : false,
      roleCd: info[14] as RoleCode,
      employeeNum: info[15],
      madn: info[16],
      hardSadn: info[17],
      fmcSadn: info[18],
      nameEn: info[19],
      nameCn: info[20],
      gradeEn: info[21],
      gradeCn: info[22],
      deptNameEn: info[23],
      deptNameCn: info[24],
      callMode: info[25],
      isPrivacyAgree: info[26] === 'Y' ? true : false,
      isValidLogin: info[27] === 'Y' ? true : false,
      employeeType: info[28] as EmployeeType,
      id: info[29]
    });
  });

  return {
    roomSeq: message.bodyList[0],
    userInfos
  } as RoomUserDataResponse;
};

export interface RoomUserStatusOfflineRequest extends ProtocolRequest {
  // 대화방SEQ(s)
  roomSeq: string;
}

export interface RoomUserStatusOfflineResponse extends ProtocolResponse {
  // 대화방SEQ(s)
  roomSeq: string;
  // 사용자SEQ(n)...
  userSeqs: number[];
}
export const encodeRoomUserStatusOffline: ProtocolEncoder<
  RoomUserStatusOfflineRequest
> = (req: RoomUserStatusOfflineRequest) => {
  const bodyList: PacketBody[] = [];

  bodyList.push({ type: PacketBodyValue.String, value: req.roomSeq });
  return bodyList;
};
export const decodeRoomUserStatusOffline: ProtocolDecoder<
  RoomUserStatusOfflineResponse
> = (message: ProtocolMessage) => {
  let userSeqs: number[] = [];
  if (message.bodyList.length > 1) {
    userSeqs = message.bodyList.slice(1);
  }
  return {
    roomSeq: message.bodyList[0],
    userSeqs
  } as RoomUserStatusOfflineResponse;
};
