import {
  ProtocolRequest,
  ProtocolResponse,
  ProtocolEncoder,
  PacketBody,
  PacketBodyValue,
  ProtocolDecoder,
  ProtocolMessage,
  BodyStringDivider,
  ProtocolStream
} from '@ucap-webmessenger/protocol';
import { UserInfo } from '../types/userInfo';

export interface BuddyInfo {
  // 사용자SEQ
  seq: number;
  // 즐.찾 여부
  isFavorit: boolean;
  // 친구여부
  isBuddy: boolean;
}

export interface BuddyRequest extends ProtocolRequest {
  // 0. 동료 씽크일시(s) cf)2019-09-24 16:51:42
  syncDate: string;
}

export interface BuddyData extends ProtocolStream {
  // n. {동료정보-S}...
  buddyInfos: BuddyInfo[];
}

export interface BuddyDetailData extends ProtocolStream {
  // n. {동료정보-S}...
  buddyInfos: UserInfo[];
}

export interface BuddyResponse extends ProtocolResponse {
  // 0. 동료 씽크일시(s) cf)2019-09-24 16:51:42
  syncDate: string;
}

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

  bodyList.push({ type: PacketBodyValue.String, value: req.syncDate || '' });
  return bodyList;
};

export const decodeBuddy: ProtocolDecoder<BuddyResponse> = (
  message: ProtocolMessage
) => {
  return {
    syncDate: message.bodyList[0]
  } as BuddyResponse;
};

export const decodeBuddyData: ProtocolDecoder<BuddyData> = (
  message: ProtocolMessage
) => {
  const buddyInfos: BuddyInfo[] = [];
  message.bodyList.forEach(buddyinfo => {
    const info = buddyinfo.split(BodyStringDivider);
    buddyInfos.push({
      seq: info[0],
      isFavorit: info[1] === 'Y' ? true : false,
      isBuddy: info[2] === 'Y' ? true : false
    });
  });
  return {
    buddyInfos
  } as BuddyData;
};

export const decodeBuddyDetailData: ProtocolDecoder<BuddyDetailData> = (
  message: ProtocolMessage
) => {
  const buddyInfos: UserInfo[] = [];
  message.bodyList.forEach(buddyinfo => {
    const info = buddyinfo.split(BodyStringDivider);
    console.log('buddyinfo', info);
    let i = 0;
    buddyInfos.push({
      seq: info[i],
      name: info[i++],
      profileImageFile: info[i++],
      grade: info[i++],
      intro: info[i++],
      companyCode: info[i++],
      hpNumber: info[i++],
      lineNumber: info[i++],
      email: info[i++],
      isMobile: info[i++] === 'Y' ? true : false,
      deptName: info[i++],
      isFavorit: info[i++] === 'Y' ? true : false,
      isBuddy: info[i++] === 'Y' ? true : false,
      isActive: info[i++] === 'Y' ? true : false,
      roleCd: info[i++],
      employeeNum: info[i++],
      madn: info[i++],
      hardSadn: info[i++],
      fmcSadn: info[i++],
      nameEn: info[i++],
      nameCn: info[i++],
      gradeEn: info[i++],
      gradeCn: info[i++],
      deptNameEn: info[i++],
      deptNameCn: info[i++],
      isPrivacyAgree: info[i++] === 'Y' ? true : false,
      isValidLogin: info[i++] === 'Y' ? true : false,
      employeeType: info[i++],
      nickName: info[i++]
    });
  });
  return {
    buddyInfos
  } as BuddyDetailData;
};
