package com.eactive.eai.transformer.message;

import java.io.UnsupportedEncodingException;

import com.eactive.eai.transformer.function.util.CodeConversion;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.util.EbcdicDumpUtil;

public class CommonEbcdicMessage extends CommonBytesMessage {
	private static final long serialVersionUID = 4540767446851935469L;
	public static final String NAME = "COMEBCDIC";

	public CommonEbcdicMessage() {
		super();
	}
	
	@Override
	public int getInt(String itemPath) {
		Item item = getItem(itemPath, true);

		if (item == null) {
			throw new InvalidAccessException("레이아웃항목이 존재하지 않음", itemPath);
		}

		Object value = item.getValue();
		if (value == null) {
			return 0;
		} else if (value instanceof byte[]) {
			try {
				return Integer.parseInt(new String((byte[]) value, "cp933").trim());
			} catch (UnsupportedEncodingException e) {
				throw new InvalidAccessException("레이아웃항목의 값이 숫자가 아님(" + value + ")", itemPath);
			}
		} else {
			throw new InvalidAccessException("레이아웃항목의 값이 문자가 아님(" + value + ")", itemPath);
		}
	}
	
	@Override
	public void setInt(String itemPath, int value) {
		int newValue = value;
		super.setInt(itemPath, newValue);
	}
	
	@Override
	public void setDefaultByteArray(String itemPath, byte[] value) {
		// EBCDIC일 경우 기본값설정은 ASCII로 등록하므로, EBCDIC으로 변경하도록 처리한다.
		byte[] ebcdic = null;
		try {
			ebcdic = CodeConversion.ascToSE(value);
			setBytes(itemPath, ebcdic);
		} catch (Exception e) {
			throw new MessageException(e.getMessage(), e);
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(
				"[COMEBCDIC message]");
		if (data != null) {
			String[] str = EbcdicDumpUtil.makeEbcdicDumpFormat((byte[]) data);
			for (int i = 0; i < str.length; i++)
				sb.append("\n    data = |" + str[i] + "|");
		}
		sb.append("\n" + super.toString());
		sb.append(
				"\n");

		return sb.toString();
	}
}
