package com.eactive.eai.inbound.remote;

import java.io.File;
import java.util.Properties;

import com.eactive.eai.adapter.ftp.Transfer;
import com.eactive.eai.batch.common.BatchDirUtil;
import com.eactive.eai.batch.common.EzgatorUtil;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.osd.OutsideVO;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.batch.rule.sysInfo.SysInfoManager;
import com.eactive.eai.batch.rule.sysInfo.SysInfoVO;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.UCMsgSenderUtil;
import com.eactive.eai.common.util.UUIDGenerator;

public class RemoteTransfer {

    // FileLoger
    static Logger logger = Logger.getLogger(Logger.LOGGER_FILEEVENT);

    private String CBS_DIR_INFO     = "CBSDirInfo";
    private String DEFAULT_SYS_CODE = "default.sys";
    private String DEFAULT_APP_CODE = "default.app";
    private String SEND_ROOT        = "send.root";
    private RemoteTransferLogVO loginfo;

    public String sendFile(String procCode, String instCode, String fileName, String startPtrnDstcd, String userId, boolean cbsYn){
        BatchJobInfoVO bjvo = null;
    	try {
        	
        	loginfo = new RemoteTransferLogVO();
            loginfo.setFileTrsmtLogID(UUIDGenerator.getUUID());
            loginfo.setSendRecvYn(RemoteTransferLogKeys.SEND);
            loginfo.setFileTrsmtStartPtrnDstcd(startPtrnDstcd);
            loginfo.setThisMsgRegsntID(userId);
        	loginfo.setBjobBzwkDstcd(procCode);
        	loginfo.setOsidInstiDstcd(instCode);
        	
        	String srcFilePath = BatchDirUtil.getResponseArchDir()
        	                     + File.separatorChar
        	                     + procCode
        	                     + File.separatorChar
        	                     + instCode;
        	loginfo.setFileTrsmtPathName(srcFilePath);
        	loginfo.setTrsmtFileName(fileName);
        	String srcFileName = srcFilePath + File.separatorChar + fileName;
        	File file = new File(srcFileName);
        	if ( !file.exists() ){
        		String msg = "E:수신 파일이 존재 하지 않습니다. + [" + srcFileName + "]";
        		logger.error(msg);
        		return msg;
        	}
        	
        	loginfo.setFileTrsmtSize(file.length());

    		
    		//거래구분 코드 설정
    		int bizCodeStartIndex  = 0;
    		int bizCodeEndIndex    = 0;
    		OutsideVO organInfo    = OutsideManager.getInstance().getOutsideInfo(procCode, instCode);
    		bizCodeStartIndex      = organInfo.getBizCdStartIdx();
    		bizCodeEndIndex        = organInfo.getBizCdEndIdx();

    		if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0;
    		if (bizCodeEndIndex   == 0 || bizCodeEndIndex   >  fileName.length()) bizCodeEndIndex = fileName.length();
    		if (bizCodeEndIndex   < 0 &&  0  <  fileName.length() + bizCodeEndIndex ) bizCodeEndIndex = fileName.length() + bizCodeEndIndex;


            // 거래 구분 코드 길이가 가변인 경우( END INDEX가 0인 경우)
            if ( organInfo.getBizCdEndIdx() == 0 ){
            	String delStr = null;
            	try {
            		Properties orgInfo = PropManager.getInstance().getProperties(
            				"TelegramInfo{" + procCode + "_" + instCode + "}");
            		delStr = orgInfo.getProperty( "del.string" );
            		if ( delStr != null && !delStr.trim().equals("")){
            			int delIndex = fileName.indexOf(delStr);
            			if ( delIndex > -1 ) {
            				bizCodeEndIndex = delIndex;
            			}
    	        	}
    	        }catch( Exception e) {}
            }
            
            String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex);
            loginfo.setBjobMsgDstcd(bizCode);
            bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode);

            String sysCd      = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_SYS_CODE);
            String applCd     = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_APP_CODE);


    		String tarSysCode = "";
    		String tarAppCode = "";

    		if ( sysCd != null && !sysCd.equals(""))
    			tarSysCode = sysCd;
    		
    		if ( applCd != null && !applCd.equals(""))
    			tarAppCode = applCd;
            
    		if ( bjvo != null ){
            	if ( bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals(""))
            		tarSysCode = bjvo.getSysCd();
            	if ( bjvo.getUapplCd()!= null && !bjvo.getUapplCd().trim().equals(""))
            		tarAppCode = bjvo.getUapplCd().toLowerCase();
            }
    		if ( cbsYn ){
    			tarSysCode = sysCd;
    		}else{
    			if ( tarSysCode.equals(sysCd) ){
        			return "";
    			}
    		}

    		// 계정계로 보내는 경우 시스템코드가 null 이 아니고 업무코드가 null 이면 보내지 않는다.
    		if ( cbsYn && bjvo != null && bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals("") && 
            		( bjvo.getUapplCd() == null || bjvo.getUapplCd().trim().equals("")) ){
            			return "";
            }

        	SysInfoVO vo = SysInfoManager.getInstance().getSysInfo(tarSysCode);
        	
        	if ( vo == null ){
        		return "E:미등록 시스템 구분 코드입니다.";
        	}

            String rmtFileTrsmtPathName = vo.getRecvDir().replaceAll("#APP#", tarAppCode);
            String rmtTrsmtFileName     = procCode + "_" + instCode + "_" + fileName;
            loginfo.setRmtFileTrsmtPathName(rmtFileTrsmtPathName);
            loginfo.setRmtTrsmtFileName(rmtTrsmtFileName);
			loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_START);
			loginfo.setFileTrsmtStartHMS(DatetimeUtil.getCurrentTimeMillis());
			try {
	            RemoteTransferLogManager.getInstance().insertRemoteTransferLog(loginfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			
			try {
				EzgatorUtil.rename(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName, rmtFileTrsmtPathName + "/" + rmtTrsmtFileName +"_"+DatetimeUtil.getCurrentTimeMillis());
			} catch (Exception e) {
			}

			EzgatorUtil.store(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName, srcFileName);
        		
            File chkFile = new File(srcFileName+BatchDirUtil.getResponseRootExt());
            chkFile.createNewFile();

            EzgatorUtil.store(vo.getSysIp(), vo.getSysPort(), rmtFileTrsmtPathName + "/" + rmtTrsmtFileName+BatchDirUtil.getResponseRootExt(), srcFileName+BatchDirUtil.getResponseRootExt());
            
			try {
				loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_SUCCESS);
				loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis());
	            RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			
			
		} catch (Throwable t) {
			logger.error(t.getMessage(), t);
	        try {
	            // 파일로그 처리
	            String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIIFE005");
	            logger.error(errMsg, t);   //Local 수신 File Event Listener 에서 오류가 발생하였습니다.
	            UCMsgSenderUtil.setUcMsg(bjvo, procCode + "_" + instCode + "_" + fileName , false, t.getMessage());
				loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_ERROR);
				loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis());
				StringBuffer sb = new StringBuffer();
				sb.append(t.getMessage()+"\n");
				sb.append(t.getClass().getCanonicalName()+"\n");
				StackTraceElement[] ste = t.getStackTrace();
				for (int inx = 0; inx < ste.length; inx++) {
					sb.append("\tat "+ ste[inx].getClassName() +"(" +ste[inx].getFileName()).append(":"+ ste[inx].getLineNumber() +")\n");
				}
				loginfo.setObstclOccurCausCtnt(new String(sb));
	            RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo);

	        } catch (Throwable e) {
	            logger.error("[Req Recv File Event] ★★★★★ 수신 File Event Listner 예외 처리 중 에러 !! ★★★★★", e);
	        }
		}
    	return "S:송신 성공[" + fileName + "]";
	}

    public String recvFile( String fullFileName, String startPtrnDstcd, String userId ) {
        BatchJobInfoVO bjvo = null;
    	try {
        	
        	loginfo = new RemoteTransferLogVO();
            loginfo.setFileTrsmtLogID(UUIDGenerator.getUUID());
            loginfo.setSendRecvYn(RemoteTransferLogKeys.RECV);
            loginfo.setFileTrsmtStartPtrnDstcd(startPtrnDstcd);
            loginfo.setThisMsgRegsntID(userId);
        	
        	String fileName = fullFileName;
        	String filePath = "/";
        	int index = fullFileName.lastIndexOf("/");
        	if ( index > -1 ){
        		fileName = fullFileName.substring(index + 1);
        		filePath = fullFileName.substring(0,index);
        	}
        	loginfo.setTrsmtFileName(fileName);
        	
        	if ( fileName.length() < 11 ){
        		return "E:파일명 길이가 충분하지 않습니다. 받은 파일명:[" + fileName + "], 파일명:[업무구분(5)_기관구분(4)_기관파일명]" ;
        	}
        	String procCode = fileName.substring(0,5);
        	String instCode = fileName.substring(6, 10);
        	loginfo.setBjobBzwkDstcd(procCode);
        	loginfo.setOsidInstiDstcd(instCode);
        	
        	String localFileName = fileName.substring(11);
        	
    		//거래구분 코드 설정
    		int bizCodeStartIndex  = 0;
    		int bizCodeEndIndex    = 0;
    		OutsideVO organInfo    = OutsideManager.getInstance().getOutsideInfo(procCode, instCode);
    		if ( organInfo == null ){
    			return "E:미등록 업무/기관 코드입니다. 업무구분[" + procCode + "]기관코드[" +  instCode + "]" ;
    		}
    		bizCodeStartIndex      = organInfo.getBizCdStartIdx();
    		bizCodeEndIndex        = organInfo.getBizCdEndIdx();

    		if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= localFileName.length()) bizCodeStartIndex = 0;
    		if (bizCodeEndIndex   <= 0 || bizCodeEndIndex   >  localFileName.length()) bizCodeEndIndex = localFileName.length();
            String bizCode = localFileName.substring(bizCodeStartIndex, bizCodeEndIndex);
            
            loginfo.setBjobMsgDstcd(bizCode);
            bjvo = DirInfoManager.getInstance().getFileInfoByDstcd(procCode, bizCode);

            String sysCd      = PropManager.getInstance().getProperty(CBS_DIR_INFO, DEFAULT_SYS_CODE);
    		String tarSysCode = "";
    		if ( sysCd != null && !sysCd.equals(""))
    			tarSysCode = sysCd;
            if ( bjvo != null ){
            	if ( bjvo.getSysCd()!= null && !bjvo.getSysCd().trim().equals(""))
            		tarSysCode = bjvo.getSysCd();
            }else{
            	return "E:미등록 업무 구분(파일) 코드입니다.";
            }

        	SysInfoVO vo = SysInfoManager.getInstance().getSysInfo(tarSysCode);
        	
        	if ( vo == null ){
        		return "E:미등록 시스템 구분 코드입니다.";
        	}

            String sendRootDir= PropManager.getInstance().getProperty(CBS_DIR_INFO, SEND_ROOT);
            
        	loginfo.setFileTrsmtPathName(sendRootDir);
            loginfo.setRmtFileTrsmtPathName(filePath);
            loginfo.setRmtTrsmtFileName(localFileName);
			loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_START);
			loginfo.setFileTrsmtStartHMS(DatetimeUtil.getCurrentTimeMillis());
			try {
	            RemoteTransferLogManager.getInstance().insertRemoteTransferLog(loginfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			long size = -1;
        	try{
        		size = FTPUtil.retrieve(vo.getSysIp(), vo.getSysPort(), vo.getUserId(), vo.getUserPassword(), fullFileName, sendRootDir, vo.getSftpYn().equals("1"), logger, Transfer.AUTH_TYPE_ID);
        	}catch( Exception t){
    	        try {
    	            // 파일로그 처리
    	            String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIIFE005");
    	            logger.error(errMsg, t);   //Local 수신 File Event Listener 에서 오류가 발생하였습니다.
    	            UCMsgSenderUtil.setUcMsg(bjvo, fileName , false, t.getMessage());
    				loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_ERROR);
    				loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis());
    				StringBuffer sb = new StringBuffer();
    				sb.append(t.getMessage()+"\n");
    				sb.append(t.getClass().getCanonicalName()+"\n");
    				StackTraceElement[] ste = t.getStackTrace();
    				for (int inx = 0; inx < ste.length; inx++) {
    					sb.append("\tat "+ ste[inx].getClassName() +"(" +ste[inx].getFileName()).append(":"+ ste[inx].getLineNumber() +")\n");
    				}
    				loginfo.setObstclOccurCausCtnt(new String(sb));
    	            RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo);

    	        } catch (Throwable e) {
    	            logger.error("[Req Recv File Event] ★★★★★ 수신 File Event Listner 예외 처리 중 에러 !! ★★★★★", e);
    	        }

        		return "E:" + t.getMessage();
        	}

			try {
				loginfo.setFileTrsmtSize(size);
				loginfo.setThisStgePrcssRsultCd(RemoteTransferLogKeys.STATUS_SUCCESS);
				loginfo.setFileTrsmtEndHMS(DatetimeUtil.getCurrentTimeMillis());
	            RemoteTransferLogManager.getInstance().updateRemoteTransferLog(loginfo);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		} catch (Throwable t) {
			logger.error(t.getMessage(), t);
			return "E:수신 실패[" + t.getMessage() +"]";
		
		}
    	
    	return "S:수신 성공[" + fullFileName +"]";
	}

}

