package com.eactive.eai.inbound.error;

import org.apache.commons.lang.StringUtils;
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.logger.EAIDBLogControl;
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 {
		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);

			String bzwkDataCtnt = vo.getBwkDataTxt();
			// db 암호화 
			bzwkDataCtnt = EncryptionManager.getInstance().encryptDBData(bzwkDataCtnt);
			vo.setBwkDataTxt(bzwkDataCtnt);
			
			if (!EAIDBLogControl.isEnable()) {
				logger.warn("DB logging is disabled.");
				logger.error(vo.toString());
				return;
			}
			
			String errCode = StringUtils.substring(vo.getErrCd(), 0, 12);
			vo.setErrCd(errCode);
			
			InboundErrorInfo entity = inboundErrorInfoMapper.toEntity(vo);
			inboundErrorInfoLoader.save(entity);
		} catch (Throwable e) {
			logger.error(e);
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIIEI001"), e);
		}
	}

}
