package com.eactive.eai.inbound.error;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.agent.encryption.EncryptionManager;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.ScpDbAgentUtil;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.data.entity.onl.inbound.error.InboundErrorInfo;
import com.eactive.eai.inbound.error.loader.InboundErrorInfoLoader;
import com.eactive.eai.inbound.error.mapper.InboundErrorInfoMapper;

@Service
@Transactional
public class InboundErrorInfoDAO extends BaseDAO {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	@Autowired
	private InboundErrorInfoLoader inboundErrorInfoLoader;

	@Autowired
	private InboundErrorInfoMapper inboundErrorInfoMapper;

	public void addInboundErrorInfo(InboundErrorInfoVO vo) throws DAOException {
		EncryptionManager manager = EncryptionManager.getInstance();
		String bzwkDataCtnt = vo.getBwkDataTxt();

		// 업무데이터를 암호화할 경우 길이가 늘어나는 문제가 있으므로 double check 함
		if ("Y".equalsIgnoreCase(manager.getEncryptYN())) {
			if (bzwkDataCtnt.length() > 2000) {
				bzwkDataCtnt = StringUtil.chunkString(bzwkDataCtnt, 2000);
			}

			String encbzwkDataCtnt = null;
			try {
				encbzwkDataCtnt = ScpDbAgentUtil.ScpEncB64(
						PropManager.getInstance().getProperties(ScpDbAgentUtil.EXT_MODULE), bzwkDataCtnt, "EUC-KR");
			} catch (Exception e) {
				logger.error("addInboundErrorInfo] scpdb_agent encryption Error - " + e.getMessage());
			}

			// double check
			if (encbzwkDataCtnt != null && encbzwkDataCtnt.length() > 4000) {
				bzwkDataCtnt = StringUtil.chunkString(bzwkDataCtnt, 500);
				try {
					encbzwkDataCtnt = ScpDbAgentUtil.ScpEncB64(
							PropManager.getInstance().getProperties(ScpDbAgentUtil.EXT_MODULE), bzwkDataCtnt, "EUC-KR");
					bzwkDataCtnt = encbzwkDataCtnt;
				} catch (Exception e) {
					logger.error("addInboundErrorInfo] scpdb_agent encryption Error - " + e.getMessage());
				}
			}
		} else {
			bzwkDataCtnt = StringUtil.chunkString(bzwkDataCtnt, 4000);
		}
		
		try {
			vo.setErrTm((vo.getErrTm()).substring(0, 16));
			vo.setErrTxt(StringUtil.chunkString(vo.getErrTxt(), 4000));

			String bizKey = vo.getBzwkSvcKeyName();
			if (bizKey == null) {
				bizKey = "";
			}
			else {
				if (bizKey.length() > 40)
					bizKey = bizKey.substring(0, 40);
			}
			vo.setBzwkSvcKeyName(bizKey);

			InboundErrorInfo entity = inboundErrorInfoMapper.toEntity(vo);
			inboundErrorInfoLoader.save(entity);
		} catch (Exception e) {
			logger.error(e);
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIIEI001"), e);
		}
	}

}
