package com.eactive.eai.common.util;

import java.util.List;
import java.util.Properties;

import com.eactive.eai.adapter.Keys;
import com.eactive.eai.common.b2badaptermapping.B2BAdapterMapFldVO;
import com.eactive.eai.common.b2badaptermapping.B2BAdapterMapManager;
import com.eactive.eai.common.b2badaptermapping.B2BAdapterMapVO;
import com.eactive.eai.common.b2bservice.B2BServiceManager;
import com.eactive.eai.common.b2bservice.B2BServiceVO;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.ServiceMessage;

// B2BRouterFCProcess 에서 기관코드/업무데이터에 맞는 Service 정보 설정
public final class B2BServiceMapper {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private B2BServiceMapper()
    {
    	
    }
   
	// 기관코드에 해당하는 서비스메시지를 EAI메시지에 설정
    public static EAIMessage setB2BService(String b2bExtnlInstiCd, EAIMessage eaiMsg) 
    throws Exception {
        
        try {
            List<ServiceMessage> svcs = eaiMsg.getSvcMsgs();
            
            boolean found = false;
            
            B2BServiceManager manager = B2BServiceManager.getInstance();
            
            // STD표준에서 12자리 고정값이므로 trim 하고 비교해야 한다.
            if(b2bExtnlInstiCd != null) b2bExtnlInstiCd = b2bExtnlInstiCd.trim();
            
            for(int p=0; p<svcs.size(); p++) {
            	B2BServiceVO b2bService = manager.getB2BServiceVO(b2bExtnlInstiCd, p+1);
            	ServiceMessage svcMsg = eaiMsg.getSvcMsg(p);
	            if(b2bService != null && svcMsg != null) {
	            	// Service Data Mapping                
	                if(b2bService.getPsvItfTp      () != null) svcMsg.setPsvItfTp      ( b2bService.getPsvItfTp      ()  );     // 수동인터페이스구분명[TSEAIHE03.ManulIntfacDsticName]
	                if(b2bService.getPsvBwkSysNm   () != null) svcMsg.setPsvBwkSysNm   ( b2bService.getPsvBwkSysNm   ()  );     // 수동시스템업무구분코드[TSEAIHE03.ManulSysBzwkDstcd]
	                if(b2bService.getPsvSysID      () != null) svcMsg.setPsvSysID      ( b2bService.getPsvSysID      ()  );     // 수동시스템ID명[TSEAIHE03.PsvSysIDName]
	                if(b2bService.getPsvSysSvcCd   () != null) svcMsg.setPsvSysSvcCd   ( b2bService.getPsvSysSvcCd   ()  );     // 수동시스템서비스구분명[TSEAIHE03.PsvSysSvcDsticName]
	                if(b2bService.getPsvSysItfTp   () != null) svcMsg.setPsvSysItfTp   ( b2bService.getPsvSysItfTp   ()  );     // 수동시스템어댑터업무그룹명[TSEAIHE03.PsvSysAdptrBzwkGroupName]
	                if(b2bService.getFlOvrCls      () != null) svcMsg.setFlOvrCls      ( b2bService.getFlOvrCls      ()  );     // 장애극복여부[TSEAIHE03.FlovrYn]
//TODO 변환은 원래값으로	                
//	                if(b2bService.getCnvEn         () != null) svcMsg.setCnvEn         ( b2bService.getCnvEn         ()  );     // 변환유무[TSEAIHE03.ChngEonot]
//	                if(b2bService.getCnvMsgID      () != null) svcMsg.setCnvMsgID      ( b2bService.getCnvMsgID      ()  );     // 변환메시지ID명[TSEAIHE03.ChngMsgIDName]
//	                if(b2bService.getBsRspMsgCprVl () != null) svcMsg.setBsRspMsgCprVl ( b2bService.getBsRspMsgCprVl ()  );     // 기본응답메시지비교내용[TSEAIHE03.BascRspnsMsgCmprCtnt]
//	                if(b2bService.getBsRspCnvEn    () != null) svcMsg.setBsRspCnvEn    ( b2bService.getBsRspCnvEn    ()  );     // 기본응답변환유무[TSEAIHE03.BascRspnsChngEonot]
//	                if(b2bService.getBsRspCnvMsgID () != null) svcMsg.setBsRspCnvMsgID ( b2bService.getBsRspCnvMsgID ()  );     // 기본응답변환메시지ID명[TSEAIHE03.BascRspnsChngMsgIDName]
//	                if(b2bService.getErrRspMsgCprVl() != null) svcMsg.setErrRspMsgCprVl( b2bService.getErrRspMsgCprVl()  );     // 오류응답메시지비교내용[TSEAIHE03.ErrRspnsMsgCmprCtnt]
//	                if(b2bService.getErrRspCnvEn   () != null) svcMsg.setErrRspCnvEn   ( b2bService.getErrRspCnvEn   ()  );     // 오류응답변환유무[TSEAIHE03.ErrRspnsChngEonot]
//	                if(b2bService.getErrRspCnvMsgID() != null) svcMsg.setErrRspCnvMsgID( b2bService.getErrRspCnvMsgID()  );     // 오류응답변환메시지ID명[TSEAIHE03.ErrRspnsChngMsgIDName]
	                                                           svcMsg.setNxtSvcPssSeq  ( b2bService.getNxtSvcPssSeq  ()  );     // 다음서비스처리번호[TSEAIHE03.NextSvcPrcssNo]
	                if(b2bService.getOutbRtnNm     () != null) svcMsg.setOutbRtnNm     ( b2bService.getOutbRtnNm     ()  );     // 아웃바운드라우팅명[TSEAIHE03.OutbndRoutName]
	                                                           svcMsg.setTmoVl         ( b2bService.getTmoVl         ()  );     // 타임아웃값[TSEAIHE03.ToutVal]
	                if(b2bService.getCpnsSvcPssCd  () != null) svcMsg.setCpnsSvcPssCd  ( b2bService.getCpnsSvcPssCd  ()  );     // 보상서비스처리구분명[TSEAIHE03.CmpenSvcPrcssDsticName]
	                // 추가
	                if(b2bService.getSupplDelYn    () != null) svcMsg.setSupplDelYn    ( b2bService.getSupplDelYn    ()  );     // 추가삭제여부[TSEAIHE02.SupplDelYn]		-[Y/N]
	                if(b2bService.getHdrCtrlDstcd  () != null) svcMsg.setHdrCtrlDstcd  ( b2bService.getHdrCtrlDstcd  ()  );     // 헤더제어구분코드[TSEAIHE02.HdrCtrlDstcd]-[01/02]삭제제추가/추가삭제
	                if(b2bService.getHdrRefClsName () != null) svcMsg.setHdrRefClsName ( b2bService.getHdrRefClsName ()  );     // 참고틀래스명[TSEAIHE02.HdrRefClsName]	-com.eactive.eai.common.header.PPSHeaderUtil
	                
//TODO 변환은 원래값으로
//	                //서비스코드로 자동생성
//	                // TRANSFORM_기동시스템업무구분코드(마지막3자리제외)_EAI서비스코드_REQ
//	                if(EAIMessageKeys.YES_FLAG.equals(svcMsg.getCnvEn()) &&
//	                		svcMsg.getCnvMsgID().trim().length() == 0	) {
////	                	if( STDMessageKeys.TELGMDMNDDSTCD_SEND.equals(eaiMsg.getKbMsg().getKBHeader().getTelgmDmndDstcd()) ) {
//                		if( STDMessageKeys.SEND_RECV_CD_SEND.equals(eaiMsg.getExtMsg().getSendRecv()) ) {
//	                		svcMsg.setCnvMsgID( makeTramsformName(eaiMsg, 1) );
//	                	}
//	                	else {
//	                		svcMsg.setCnvMsgID( makeTramsformName(eaiMsg, 2) );
//	                	}
//	                }
//	                
//	                if(EAIMessageKeys.YES_FLAG.equals(svcMsg.getBsRspCnvEn()) &&
//	                		svcMsg.getBsRspCnvMsgID().trim().length() == 0	) {
//	                	svcMsg.setBsRspCnvMsgID( makeTramsformName(eaiMsg, 2) );
//	                }
//	                
//	                if(EAIMessageKeys.YES_FLAG.equals(svcMsg.getErrRspCnvEn()) &&
//	                		svcMsg.getErrRspCnvMsgID().trim().length() == 0	) {
//	                	svcMsg.setErrRspCnvMsgID( makeTramsformName(eaiMsg, 3) );
//	                }
	                
	                
	                eaiMsg.setSvcMsgs(p, svcMsg);
	                
	                	//              KESA B2Bi 의 외부기관코드에 등록할 경우
	                //----------------------------------------------------
	                // KESA -> KBMessage 로 변경 : 20080324 DHLEE
	                //----------------------------------------------------
	                /*
	                try {
	                    Object b2bEachMsg = eaiMsg.getKesaMsg().getKesaEachMsg();
	                    if(b2bEachMsg instanceof KESAB2BIMessage) {
	                        ((KESAB2BIMessage)b2bEachMsg).setBBizCode(b2bExtnlInstiCd);
	                    }
	                } catch(Exception e) { ; }
	                */
	//                
	//                KBCommon kbcommon = eaiMsg.getKbMsg().getKBCommon();
	//                try {
	//                    if(KBMessageKeys.WTINEXTNLDSTCD_EX.equals( kbcommon.getInoPartlDstcd() )) {
	//                        kbcommon.setOsidInstiCd(b2bExtnlInstiCd);
	//                    }
	//                } catch(Exception e) { ; }
	//                
	                //----------------------------------------------------
	                found = true;	                
	            }
            }
            
            if(found) {
            	return eaiMsg;
            }
            else {
            	return null;
            }
        }
        catch (Exception e) {
            // B2B 기관코드에 해당하는 서비스메시지 설정 중 오류가 발생.
        	logger.error("setB2BService error", e);
            throw new Exception(ExceptionUtil.getErrorCode(e,"RECEAICBS001"));
        }
    }
    
    private static String makeTramsformName(EAIMessage eaiMsg, int reqIndex) {
    	String transformName = "";
    	
    	String transformNameFormat = "TRANSFORM_%s_%s_%s";
    	
    	String eaiSvcPrefix = eaiMsg.getEAISvcCd().trim();
    	if(eaiSvcPrefix.length() > 3) {
    		eaiSvcPrefix = eaiSvcPrefix.substring(0, eaiSvcPrefix.length() -3);
    	}
    	
    	if(reqIndex == 1) {
    		transformName = String.format(transformNameFormat, eaiMsg.getBwkCls().trim(), eaiSvcPrefix, "REQ");
    	}
    	else if(reqIndex == 2) {
    		transformName = String.format(transformNameFormat, eaiMsg.getBwkCls().trim(), eaiSvcPrefix, "RES");
    	}
    	else {
    		transformName = String.format(transformNameFormat, eaiMsg.getBwkCls().trim(), eaiSvcPrefix, "ERR");
    	}
    	return transformName;
    }
    
    // 업무데이터에 해당하는 Addpater를 EAI메시지에 설정
    public static EAIMessage setB2BAdapter(String b2bExtnlInstiCd, String bzwkVal, EAIMessage eaiMsg, Properties callProp) 
    throws Exception {
        
        try {
            String eaiSvcCd = eaiMsg.getEAISvcCd();
            int svcSeq = eaiMsg.getSvcPssSeq();
            B2BAdapterMapManager manager = B2BAdapterMapManager.getInstance();
            B2BAdapterMapVO map = manager.getB2BAdapterMap(eaiSvcCd);
            
             if(map == null) {
                return null;
                // throw new Exception("B2B 업무데이터["+bzwkVal+"]의 라우팅룰이 정의되지 않았습니다.");
            }
            
            B2BAdapterMapFldVO fvo = map.getB2BAdapterMapFld(b2bExtnlInstiCd, bzwkVal);
            
            if(fvo == null) {
                // 등록된 정보가 없는 경우 NULL을 return
            	return null;
            }
            
            // Socket Adapter일 경우에
            ServiceMessage svcMsg = eaiMsg.getCurrentSvcMsg();
            String adapterGroupName = fvo.getAdapterGroupName();
            String adapterName = fvo.getAdapterName();
            if(adapterName != null && adapterName.length() > 0 && !"DEFAULT".equals(adapterName) ) {
            	svcMsg.setPsvSysItfTp(adapterGroupName);
            	callProp.setProperty(Keys.OUT_ADAPTER_NAME, adapterName);
            }
            else {
            	svcMsg.setPsvSysItfTp(adapterGroupName);
            }
            
            eaiMsg.setSvcMsgs(svcSeq - 1, svcMsg);
        }
        catch (Exception e) {
            // B2B 업무데이터에 대한 B2B Adapter 매핑 중 오류가 발생.
            throw new Exception(ExceptionUtil.getErrorCode(e,"RECEAICBS002"));
        }
        return eaiMsg;
    }
}