package com.eactive.eai.common.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.UncategorizedSQLException;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.common.duplication.DuplicationGuidDataVo;
import com.eactive.eai.common.duplication.DuplicationGuidLogVo;
import com.eactive.eai.common.duplication.loader.DuplicationGuidDataLogger;
import com.eactive.eai.common.duplication.loader.DuplicationGuidLogLogger;
import com.eactive.eai.common.duplication.mapper.DuplicationGuidDataMapper;
import com.eactive.eai.common.duplication.mapper.DuplicationGuidLogMapper;
import com.eactive.eai.common.logger.EAIDBLogControl;
import com.eactive.eai.data.entity.onl.duplication.DuplicationGuidData;
import com.eactive.eai.data.entity.onl.duplication.DuplicationGuidLog;
import com.eactive.eai.inbound.processor.ProcessVO;

public class DuplicationGuidLogUtil {

	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static void insert(String guid, String channelTypeCd, ProcessVO processVo, Object message) throws Exception {
		if (EAIDBLogControl.isEnable()) {
			try {
				DuplicationGuidLogLogger service = ApplicationContextProvider.getContext()
						.getBean(DuplicationGuidLogLogger.class);
				DuplicationGuidLogMapper mapper = ApplicationContextProvider.getContext()
						.getBean(DuplicationGuidLogMapper.class);
				DuplicationGuidLogVo vo = new DuplicationGuidLogVo();
				vo.setGuid(guid);
				vo.setChannelCode(channelTypeCd);
				vo.setInstanceName(processVo.getServerName());
				vo.setEaisvcname(processVo.getEaiSvcCd());
				vo.setRecvDatetime(DatetimeUtil.getCurrentTime(processVo.getErrTm()));

				DuplicationGuidLog entity = mapper.toEntity(vo);
				service.save(entity);
			} catch (DataIntegrityViolationException | UncategorizedSQLException e) {
				DuplicationGuidDataLogger service = ApplicationContextProvider.getContext()
						.getBean(DuplicationGuidDataLogger.class);
				DuplicationGuidDataMapper mapper = ApplicationContextProvider.getContext()
						.getBean(DuplicationGuidDataMapper.class);
				DuplicationGuidDataVo vo = new DuplicationGuidDataVo();
				vo.setUuid(processVo.getUuid());
				vo.setChannelCode(channelTypeCd);
				vo.setGuid(guid);
				vo.setInstanceName(processVo.getServerName());
				vo.setEaisvcname(processVo.getEaiSvcCd());
				vo.setRecvDatetime(DatetimeUtil.getCurrentTime(processVo.getErrTm()));
				vo.setBizData(toStringBizData(message, processVo.getAdapterGroupName()));

				DuplicationGuidData entity = mapper.toEntity(vo);
				service.save(entity);
				throw new Exception("GUID duplication error guid=" + guid);
			} catch (Throwable th) {
				logger.error("[" + guid + "] Insert Guid Log Error. - " + th.getMessage(), th);
			}
		}
	}

	private static String toStringBizData(Object message, String adapterGroupName) {
		String msg = null;
		if (message == null) {
			msg = "null";
		} else {
			if (message instanceof byte[]) {
				AdapterManager adapterManager = AdapterManager.getInstance();
				AdapterGroupVO srcAdapterGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
				if (srcAdapterGrpVO == null) {
					msg = new String((byte[]) message);
				} else {
					String charset = StringUtils.defaultIfBlank(srcAdapterGrpVO.getMessageEncode(),
							Charset.defaultCharset().name());
					try {
						msg = new String((byte[]) message, charset);
					} catch (UnsupportedEncodingException e) {
						logger.warn("msg encode error", e);
						msg = new String((byte[]) message);
					}
				}

			} else if (message instanceof String) {
				msg = (String) message;
			} else {
				msg = "invaild message [" + message.getClass().getName() + "] " + message.toString();
			}
		}
		return msg;
	}
}