package com.eactive.eai.adapter.ftp;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

import com.eactive.eai.adapter.socket.config.ConfigurationContext;
import com.eactive.eai.adapter.socket.service.SocketService;
import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;

public class FTPBG extends Transfer implements SocketService{

    private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
    private static final String SEND_SHELL = "send.shell";
    private static final String RECV_SHELL = "recv.shell";

	public void sendFile(BatchDoc batchDoc) throws Exception {
		logger.info("[FTPSH] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");

		firstActivity = System.currentTimeMillis();
		setLastActivity();
		BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
		//Shell 명령어를 Runtime 으로 실행
		try {
	        String propName = PROP_GROUP_NAME_PREFIX + "{" +
		                      batchDoc.getBatchMsg().getHeader().getProcessCode() +
		                      "_" +
		                      batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
	        
	        PropManager pmanager = PropManager.getInstance();

			String shellCommand = pmanager.getProperties(propName).getProperty(SEND_SHELL);
			if ( shellCommand == null ){
				throw new Exception("해당 기관에 송신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_SHELL);
			}
			String[] command = new String[4];
			command[0] = shellCommand;
			command[1] = batchDoc.getBatchMsg().getHeader().getFilePath();
			command[2] = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
			command[3] = batchDoc.getBatchMsg().getHeader().getFileName();
			
			setFileHeaderAndTrailer(batchDoc, new File(batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName()));
			
			batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
			LogUtil.setLogFileStart(batchDoc);
			runSystemScript( command );
			batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
			LogUtil.setLogFileEnd(batchDoc);

		} catch(Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI002";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
			batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
            LogUtil.setErrorLog(batchDoc, ex.getMessage());
            logger.error( errMsg, ex );
            throw ex;
		} finally {
			BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
			this.disconnect();
        }
		logger.info("[FTPSH] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");		
	}
	
	public void recvFile(BatchDoc batchDoc) throws Exception {
		logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
		firstActivity = System.currentTimeMillis();
		setLastActivity();
		BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
		String fileName = batchDoc.getBatchMsg().getHeader().getBizCode();
		//Shell 명령어를 Runtime 으로 실행
		try {
	        String propName = PROP_GROUP_NAME_PREFIX + "{" +
		                      batchDoc.getBatchMsg().getHeader().getProcessCode() +
		                      "_" +
		                      batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
	        
	        PropManager pmanager = PropManager.getInstance();

			String shellCommand = pmanager.getProperties(propName).getProperty(RECV_SHELL);
			if ( shellCommand == null ){
				throw new Exception("해당 기관에 수신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_SHELL);
			}
			
			String[] command = new String[3];
			command[0] = shellCommand;
			command[1] = batchDoc.getBatchMsg().getHeader().getFilePath();
			command[2] = fileName;
			
			batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
			runSystemScript( command );
			File recvDir = new File(batchDoc.getBatchMsg().getHeader().getFilePath());
			File[] recvFiles = recvDir.listFiles();
			for( int inx = 0; inx < recvFiles.length; inx++){
				File recvFile = recvFiles[inx];
				if ( recvFile.getName().startsWith(fileName)){
					File rcvRootFile = new File( StringUtil.realToRootDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName() );
					File rcvArchFile = new File( StringUtil.realToArchDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName());
	                batchDoc.getBatchMsg().getHeader().setFileName(recvFile.getName());
	    			LogUtil.setLogFileStart(batchDoc);
	            	batchDoc.getBatchMsg().getHeader().setFileSize(recvFile.length());
	            	batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
	                setFileHeaderAndTrailer(batchDoc, recvFile);
	                recvFile.renameTo(rcvArchFile);
	    			rcvRootFile.createNewFile();
	    			batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
	    			LogUtil.setLogFileEnd(batchDoc);
				}
			}
		
		} catch(Exception ex) {
			String noFileMessage = fileName + " NOT EXIST";
            String[] msgArgs = new String[1];
            msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI002";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
			batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
			if ( ex.getMessage().indexOf(noFileMessage) < 0 ){
	            batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
	            LogUtil.setErrorLog(batchDoc, ex.getMessage());
	            logger.error( errMsg, ex );
	            throw ex;
			}
		} finally {
			BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
			this.disconnect();
        }
		logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");		
	}

	@Override
	public void shutdown() {
		
	}

	@Override
	public Socket getCurrentSocket() {
		return null;
	}

	@Override
	public boolean connect() {
		return false;
	}

	@Override
	public ConfigurationContext getContext() {
		return null;
	}

	@Override
	public void setControl(Object control) {
		
	}

	@Override
	public void notifyMessage() {
		
	}

	@Override
	public boolean idle(long timeout) {
		return false;
	}

	@Override
	public int getCurrentState() {
		return 0;
	}

	@Override
	public boolean isConnected() throws IOException {
		return false;
	}

	@Override
	public boolean isActive() {
		return false;
	}

	@Override
	public void checkActivity() {
		
	}

	@Override
	public String getRemoteIPAddress() {
		return null;
	}

	@Override
	public void setLastActivity() {
		lastActivity = System.currentTimeMillis();
	}

	@Override
	public long getFirstActivity() {
		return firstActivity;
	}

	@Override
	public long getLastActivity() {
		return lastActivity;
	}
}