package com.eactive.eai.common.exception;

import java.util.HashMap;
import java.util.Properties;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.ElinkAdapter;
import com.eactive.eai.adapter.ElinkAdapterFactory;
import com.eactive.eai.adapter.Keys;
import com.eactive.eai.adapter.wca.SNAProperties;
import com.eactive.eai.common.logger.EAILogSender;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.message.ServiceMessage;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.message.StandardMessage;

public class ErrorResponseSender {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static HashMap<String,String> errCodeMap = new HashMap();
	
	static {
		errCodeMap.put("RECEAIOSA001", "RECEAICEU10");
		errCodeMap.put("RECEAIOEP001", "RECEAICEU10");
		errCodeMap.put("RECEAIOHP001", "RECEAICEU10");
		errCodeMap.put("RECEAIOHP003", "RECEAICEU10");
		errCodeMap.put("RECEAIOSP001", "RECEAICEU10");
		errCodeMap.put("RECEAIOSP002", "RECEAICEU10");
		errCodeMap.put("RECEAIOSP003", "RECEAICEU10");
		errCodeMap.put("RECEAIOSP004", "RECEAICEU10");
		errCodeMap.put(EAIMessageKeys.EAI_BLOCKED_CODE, "RECEAICEU30"); // 거래통제 에러
		errCodeMap.put(EAIMessageKeys.EAI_INFLOW_BLOCKED_CODE, "RECEAICEU30"); // 유량제어 에러
	}
	
	/** 
    * 1. 기능 :  에러크드 재조합
    * 2. 처리 개요 : 
    *     - RECEAICEU10X - 호출에러 
    *     - RECEAICEU20X - 변환에러
    *     - X (1:취급요청, 2:취급응답, 3:개설요청, 4:개설응답 
    * 3. 주의사항 
    *
    * @param   eaiMessage         : EAIMessage
    * @exception    Exception    SQLException
    **/
	private static String convertErrorCode(String errCode, String guCode) {
		String newErrCode = "";
		newErrCode = errCodeMap.get(errCode);
		
		if(newErrCode == null) {
			// 통신에러 코드이거나 TUXEDO 통신에러코드일 경우 
			if( errCode!= null && errCode.startsWith("RECEAIOTC9") ) {
				newErrCode = "RECEAICEU10";
			}
			else {
				newErrCode = "RECEAICEU20";
			}
		}
		return newErrCode + guCode;
	}
	
    private static byte[] makeStandardMessageData(EAIMessage eaiMessage, String msgType
    		, String charset) throws Exception{
//    	InterfaceMapper mapper = eaiMessage.getMapper();
    	StandardMessage standardMessage = eaiMessage.getStandardMessage();
//    	String operationEnv = mapper.getOperationEnv(standardMessage);
/*    	
//    	if(MessageType.JSON.equals(msgType) || MessageType.UJSON.equals(msgType)) {
    	if(MessageType.JSON.equals(msgType)) {
    		return standardMessage.toJson().getBytes(charset);
    	}
//    	else if(MessageType.XML.equals(msgType) || MessageType.UXML.equals(msgType)) {
    	else if(MessageType.XML.equals(msgType)) {
    		return standardMessage.toXML().getBytes(charset);
    	}
    	else if(MessageType.ASC.equals(msgType)) {
    		return standardMessage.toByteArray(charset);
    	}
    	else {
    		throw new Exception("Unsupported msgType - " + msgType);
    	}
*/
    	return standardMessage.getDataBytes(msgType, charset);
    }
    
	public static void sendErrorResponseMessage(EAIMessage eaiMessage, String charset) {
		
		boolean isError = false;
		String errorMsg = "";
		try {
		
			// 1. EAI메시지 파싱
			ServiceMessage smsg = eaiMessage.getCurrentSvcMsg();
			String adapterGroupName  = smsg.getPsvSysItfTp();
			
			// 2. 송신어댑터 분석
			AdapterManager adapterManager = AdapterManager.getInstance();
			AdapterGroupVO adapterGroup = adapterManager.getAdapterGroupVO(adapterGroupName);
			
			// ASC/EBC/JOB/FML/F32/XML
			String msgType     = adapterGroup.getMessageType();
			// SNA/SOC/NET/HTT
			String adapterType = adapterGroup.getType();
		
			// 3. 송신메시지 생성
			byte[] reqBytes = null;
			try {
				reqBytes = makeStandardMessageData(eaiMessage, msgType, charset);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			//ExtMessageConverter.normalAsyncSend(eaiMessage, msgType);
			
			AdapterVO adptVO = adapterGroup.nextAdapterVO();
			
			// 가용 Adapter가 없는 경우
			if(adptVO == null) {
				String[] msgArgs = new String[1];
				msgArgs[0] = String.valueOf(adapterGroupName);
				String resMsg = ExceptionUtil.make("RECEAIOSA900", msgArgs);
				throw new Exception(resMsg);
			}
            Properties prop = null;
            
            if( Keys.TYPE_HTTP.equals(adapterGroup.getType()) ) {
            	AdapterPropManager manager = AdapterPropManager.getInstance();
            	prop = manager.getProperties(adptVO.getPropGroupName());
            	prop.put("adapterName", adptVO.getName());
            }
            else {
            	prop = new Properties();
            }
			prop.setProperty("ADAPTER_GROUP_NAME", adapterGroupName);
			
			//-------------------------------------------
			// SNA Property 설정 : 2010.02.07
			prop.setProperty(SNAProperties.TRAN_KEY, eaiMessage.getSvcOgNo()); // UUID
			prop.setProperty(SNAProperties.ADAPTER_GRP_NAME, adapterGroupName);        
			prop.setProperty(SNAProperties.LU_NAME, " ");        
			prop.setProperty(SNAProperties.DATA_TYPE, SNAProperties.DATA_TYPE_NORMAL);

            
            String adapterName = adptVO.getName();
            
			prop.setProperty(SNAProperties.ADAPTER_NAME, adapterName); 
			
			prop.setProperty(SNAProperties.TRAN_MODE, SNAProperties.TRAN_MODE_NONRESPONSE);
			//-------------------------------------------
			
			// 4. 비동기 송신
		
            ElinkAdapterFactory factory = ElinkAdapterFactory.newInstance();            
            ElinkAdapter adapter = null;
            adapter = factory.getElinkAdapter(adapterType);
        	adapter.callService(adapterGroupName, prop, reqBytes, new Properties());
        } catch(Exception e) {
            logger.error("sendErrorResponseMessage error", e);
            errorMsg = e.getMessage();
            isError = true;
        }
        
        // 5. 에러로그(900)저장
        // 2009.10.06
        // 송신에러 와 정상일 경우에 대한 로그 처리
        if(isError) {
//        	eaiMessage.setRspErrCd("RECEAICEU999"); // 에러응답 송신 에러         	
        	String rspErrMsg = eaiMessage.getRspErrMsg() + errorMsg;
//        	eaiMessage.setRspErrMsg(rspErrMsg);
        	eaiMessage.setRspErr("RECEAICEU999", rspErrMsg);
        }
        
        eaiMessage.setLogPssSno(900);
        try{
            EAILogSender.send(eaiMessage, null);
        }catch(Exception e){
            logger.error("ExceptionHandler] EAILogSender send fail");
//            e.printStackTrace();
        }
	}
	
	
}
