package com.eactive.eai.util;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.adapter.socket2.protocol.ByteMessage;
import com.eactive.eai.inbound.processor.ProcessVO;

public class SimHeaderUtil {
	public static int EAISVCCD_LEN = 30;// eaisvccd
	public static int BZWKSVCKEY_LEN = 40;// 업무추출키
	public static int INSTITUTIONCODE_LEN = 10;// 기관코드
	public static int TEMP_LEN = 20;// 임시

	// TODO : check encoding or remove this class logic
	private static byte[] toByteArray(Object obj) {
		byte[] data = null;
		if (obj instanceof byte[]) {
			data = (byte[]) obj;
		} else if (obj instanceof String) {
			data = ((String) obj).getBytes();
		}
		return data;
	}

	public static byte[] addSimHeader(String eaiSvcCd, String InstitutionCode, Object obj) {
		byte[] data = toByteArray(obj);

		ByteMessage bm = new ByteMessage();
		bm.append(StringUtils.rightPad(eaiSvcCd, EAISVCCD_LEN));
		bm.append(StringUtils.rightPad("", BZWKSVCKEY_LEN));
		bm.append(StringUtils.rightPad(InstitutionCode, INSTITUTIONCODE_LEN));
		bm.append(StringUtils.rightPad("", TEMP_LEN));
		bm.append(data);
		return bm.getBytes();
	}

	// 시뮬레이터에서 온 데이터중 SIM Header 를 vo에 셋팅
	public static ProcessVO getSimHeader(ProcessVO vo, byte[] obj) throws Exception {
		byte[] data = toByteArray(obj);
		ByteMessage bm = new ByteMessage(data);
		String eaiSvcCdKey = new String(bm.getBytes(0, EAISVCCD_LEN));
		String simKey = new String(bm.getBytes(EAISVCCD_LEN, BZWKSVCKEY_LEN));
		String instcdKey = new String(bm.getBytes(EAISVCCD_LEN + BZWKSVCKEY_LEN, INSTITUTIONCODE_LEN));
		String tempKey = new String(bm.getBytes(EAISVCCD_LEN + BZWKSVCKEY_LEN + INSTITUTIONCODE_LEN, TEMP_LEN));

		vo.setSelectedKey(simKey.trim());
		vo.setInAdapterOsidInstiNo(instcdKey.trim());
		vo.setEaiSvcCd(eaiSvcCdKey.trim());

		return vo;
	}

	// 시뮬레이터에서 온 데이터중 SIM Header제거 하고 데이터만 추출
	public static byte[] getSimData(Object obj) {
		byte[] data = toByteArray(obj);
		ByteMessage bm = new ByteMessage((byte[]) data);
		return bm.getBytes(EAISVCCD_LEN + BZWKSVCKEY_LEN + INSTITUTIONCODE_LEN + TEMP_LEN);
	}
}
