package com.eactive.eai.batch.common;

import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;

import com.eactive.eai.common.util.Logger;


public class BatchDirUtil
{

	//파일로거
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private static void makeDirBatch(String dirSuffix, boolean makeParent) throws Exception {
		int successCnt = 0;
//		if ( FileUtil.mkdir(getRequestRealDir()   +"/"+ dirSuffix, makeParent) ) successCnt++;
//		if ( FileUtil.mkdir(getRequestRootDir()   +"/"+ dirSuffix, makeParent) ) successCnt++;
		if ( FileUtil.mkdir(getRequestArchDir()   +"/"+ dirSuffix, makeParent) ) successCnt++; //송신ARCH  - /fepftp/fep/batch/SENDARCH
		if ( FileUtil.mkdir(getRequestErrorDir()  +"/"+ dirSuffix, makeParent) ) successCnt++; //송신ERROR - /fepftp/fep/batch/SENDERROR
		if ( FileUtil.mkdir(getRequestRootDir()   +"/"+ dirSuffix, makeParent) ) successCnt++; //송신      - /fepftp/fep/batch/snd
		if ( FileUtil.mkdir(getResponseRealDir()  +"/"+ dirSuffix, makeParent) ) successCnt++; //수신REAL  - /fepftp/fep/batch/RECVREAL
		if ( FileUtil.mkdir(getResponseRootDir()  +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ROOT  - /fepftp/fep/batch/RECVROOT
		if ( FileUtil.mkdir(getResponseArchDir()  +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ARCH  - /fepftp/fep/batch/RECVARCH
		if ( FileUtil.mkdir(getResponseErrorDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ERROR - /fepftp/fep/batch/RECVERROR
//		if ( FileUtil.mkdir(getResponseNasDir()   +"/"+ dirSuffix, makeParent) ) successCnt++;
//		if ( FileUtil.mkdir(getResponseChkDir()   +"/"+ dirSuffix, makeParent) ) successCnt++; 
//		if ( FileUtil.mkdir(getResSendRealDir()   +"/"+ dirSuffix, makeParent) ) successCnt++; //
//		if ( FileUtil.mkdir(getResSendArchDir()   +"/"+ dirSuffix, makeParent) ) successCnt++;
				
		//		add by dhjeong at 2009.09.21
		if ( FileUtil.mkdir(getReqRecvRootDir()   +"/"+ dirSuffix, makeParent) ) successCnt++; //요구수신ROOT  - /fepftp/fep/batch/REQROOT
		if ( FileUtil.mkdir(getReqRecvErrorDir()  +"/"+ dirSuffix, makeParent) ) successCnt++; //요구수신ERROR - /fepftp/fep/batch/REQERROR
		
		if (successCnt < 8) logger.error("★★★★★ 배치 송수신 디렉토리 생성 실패 !! ★★★★★ ( 총 8 개 중 "+ successCnt +" 개 생성됨 )");
	}

	private static void removeDirBatch(String dirSuffix, boolean removeChild) throws Exception {
		int successCnt = 0;
//		if ( FileUtil.rmdir(getRequestRealDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
//		if ( FileUtil.rmdir(getRequestRootDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getRequestArchDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getRequestErrorDir()  +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getRequestRootDir()  +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getResponseRealDir()  +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getResponseRootDir()  +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getResponseArchDir()  +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getResponseErrorDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
//		if ( FileUtil.rmdir(getResponseNasDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
//		if ( FileUtil.rmdir(getResponseChkDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
//		if ( FileUtil.rmdir(getResSendRealDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
//		if ( FileUtil.rmdir(getResSendArchDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
		
		//		add by dhjeong at 2009.09.21
		if ( FileUtil.rmdir(getReqRecvRootDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
		if ( FileUtil.rmdir(getReqRecvErrorDir()   +"/"+ dirSuffix, removeChild) ) successCnt++;
		
		if (successCnt < 8) logger.error("★★★★★ 배치 송수신 디렉토리 삭제 실패 !! ★★★★★ ( 총 8 개 중 "+ successCnt +" 개 삭제됨 )");
	}

//	private static void renameDirBatch(String fromDirSuffix, String toDirSuffix, boolean makeDestDir) throws Exception {
//		int successCnt = 0;
//		if ( FileUtil.move(getRequestRealDir()   +"/"+ fromDirSuffix, getRequestRealDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getRequestRootDir()   +"/"+ fromDirSuffix, getRequestRootDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getRequestArchDir()   +"/"+ fromDirSuffix, getRequestArchDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getRequestErrorDir()  +"/"+ fromDirSuffix, getRequestErrorDir()  +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseRealDir()  +"/"+ fromDirSuffix, getResponseRealDir()  +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseRootDir()  +"/"+ fromDirSuffix, getResponseRootDir()  +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseArchDir()  +"/"+ fromDirSuffix, getResponseArchDir()  +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseErrorDir() +"/"+ fromDirSuffix, getResponseErrorDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseNasDir()   +"/"+ fromDirSuffix, getResponseNasDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResponseChkDir()   +"/"+ fromDirSuffix, getResponseChkDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResSendRealDir()   +"/"+ fromDirSuffix, getResSendRealDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getResSendArchDir()   +"/"+ fromDirSuffix, getResSendArchDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		
//		//		add by dhjeong at 2009.09.21
//		if ( FileUtil.move(getReqRecvRootDir()   +"/"+ fromDirSuffix, getReqRecvRootDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		if ( FileUtil.move(getReqRecvErrorDir()   +"/"+ fromDirSuffix, getReqRecvErrorDir()   +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//		
//		if (successCnt < 14) logger.error("★★★★★ 배치 송수신 디렉토리명 변경 실패 !! ★★★★★ ( 총 14 개 중 "+ successCnt +" 개 변경됨 )");
//	}

	//==================================================================================================================
	public static void makeDirProcess( String processCode ) throws Exception {
		logger.debug("■ 업무구분 디렉토리 생성 Start......");
		makeDirBatch(processCode, true);  //true : 상위 디렉토리 미존재시 자동 생성함
	}

	public static void removeDirProcess(String processCode) throws Exception {
		logger.debug("■ 업무구분 디렉토리 삭제 Start......");
		removeDirBatch(processCode, false);  //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
	}

//	public static void renameDirProcess(String fromProcessCode, String toProcessCode) throws Exception {
//		logger.debug("■ 업무구분 디렉토리명 변경 Start......");
//		renameDirBatch(fromProcessCode, toProcessCode, false);  //false: 목적 경로 미존재시 생성 안함
//	}


	//==================================================================================================================
	public static void makeDirOrgan(String processCode, String organCode) throws Exception {
		logger.debug("■ 대외기관 디렉토리 생성 Start......");
		makeDirBatch(processCode +"/"+ organCode, true);  //true : 상위 디렉토리 미존재시 자동 생성함

//		//생성된 대외기관 디렉토리 밑에 해당 업무의 전체 거래구분그룹 디렉토리도 함께 생성
//		ArrayList<DirInfoVO> bizGroupList = DirInfoManager.getInstance().getDirInfoByBatchCode(processCode);
//		for (int i=0; i<bizGroupList.size(); i++) {
//			DirInfoVO info = bizGroupList.get(i);
//			makeDirBatch(processCode +"/"+ organCode +"/"+ info.getBizGroupCd(), true);  //true : 상위 디렉토리 미존재시 자동 생성함
//		}
	}

	public static void removeDirOrgan(String processCode, String organCode) throws Exception {
		logger.debug("■ 대외기관 디렉토리 삭제 Start......");
		removeDirBatch(processCode +"/"+ organCode, false);  //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
	}

//	public static void renameDirOrgan(String processCode, String fromOrganCode, String toOrganCode) throws Exception {
//		logger.debug("■ 대외기관 디렉토리명 변경 Start......");
//		renameDirBatch(processCode +"/"+ fromOrganCode, processCode +"/"+ toOrganCode, false);  //false: 목적 경로 미존재시 생성 안함
//	}

	//==================================================================================================================
//	public static void makeDirBizGroup(String processCode, String bizGroupCode) throws Exception {
//		logger.debug("■ 거래구분그룹 디렉토리 생성 Start......");
//		//해당 업무의 모든 대외기관 디렉토리 밑에 거래구분그룹 디렉토리 생성
//		ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
//		for (int i=0; i<organList.size(); i++) {
//			OutsideVO info = organList.get(i);
//			makeDirBatch(processCode +"/"+ info.getOsdCode() +"/"+ bizGroupCode, true);  //true : 상위 디렉토리 미존재시 자동 생성함
//		}
//	}

//	public static void removeDirBizGroup(String processName, String processCode, String bizGroupName, String bizGroupCode) throws Exception {
//		logger.debug("■ 거래구분그룹 디렉토리 삭제 Start......");
//		//해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리 삭제
//		ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
//		for (int i=0; i<organList.size(); i++) {
//			OutsideVO info = organList.get(i);
//			removeDirBatch(processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ bizGroupName +"_"+ bizGroupCode, false);  //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
//		}
//	}

//	public static void renameDirBizGroup(String processName, String processCode, String fromBizGroupName, String fromBizGroupCode, String toBizGroupName, String toBizGroupCode) throws Exception {
//		logger.debug("■ 거래구분그룹 디렉토리명 변경 Start......");
//		//해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리명 변경
//		ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
//		for (int i=0; i<organList.size(); i++) {
//			OutsideVO info = organList.get(i);
//			renameDirBatch(processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ fromBizGroupName +"_"+ fromBizGroupCode,
//			               processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ toBizGroupName   +"_"+ toBizGroupCode, false);  //false: 목적 경로 미존재시 생성 안함
//		}
//	}

	//요구송신 디렉토리 프라퍼티 키 정보
	public static final String REQUEST_SND_DIR_INFO  = "FileEventDirInfo";
//	public static final String REQUEST_SND_REAL_DIR  = "BASE_REAL_DIR";
	public static final String REQUEST_SND_ROOT_DIR  = "BASE_SEND_DIR";
	public static final String REQUEST_SND_ARCH_DIR  = "BASE_ARCH_DIR";
	public static final String REQUEST_SND_ERROR_DIR = "BASE_ERROR_DIR";
	public static final String REQUEST_SND_ROOT_EXT  = "snd.root.ext";

	//응답수신 디렉토리 프라퍼티 키 정보
	public static final String RESPONSE_RCV_DIR_INFO  = "ResponseRcvDirInfo";
	public static final String RESPONSE_RCV_REAL_DIR  = "rcv.real.directory";
	public static final String RESPONSE_RCV_ROOT_DIR  = "rcv.root.directory";
	public static final String RESPONSE_RCV_ARCH_DIR  = "rcv.arch.directory";
	public static final String RESPONSE_RCV_ERROR_DIR = "rcv.error.directory";
//	public static final String RESPONSE_RCV_NAS_DIR   = "rcv.nas.directory";
//	public static final String RESPONSE_RCV_CHK_DIR   = "rcv.chk.directory";
	public static final String RESPONSE_RCV_ROOT_EXT  = "rcv.root.ext";

	// 응답송신용 디렉토리 프라퍼티 키 정보  20060425 add by khs
//	public static final String RESPONSE_SND_DIR_INFO  = "ResponseSndDirInfo";
//	public static final String RESPONSE_SND_REAL_DIR  = "snd.real.directory";
//	public static final String RESPONSE_SND_ARCH_DIR  = "snd.arch.directory";
	
//	//	요구송신 디렉토리 프라퍼티 키 정보 (이벤트 스케줄러의 스케줄 기반 요구송신 디렉토리)
//	//	add by kscheon at 2008.10.27
//	public static final String SCH_REQUEST_SND_DIR_INFO  = "SchedulerFileEventDirInfo";
//	public static final String SCH_REQUEST_SND_REAL_DIR  = "BASE_REAL_DIR";
//	public static final String SCH_REQUEST_SND_ROOT_DIR  = "BASE_ROOT_DIR";
//	public static final String SCH_REQUEST_SND_ARCH_DIR  = "BASE_ARCH_DIR";
//	public static final String SCH_REQUEST_SND_ERROR_DIR = "BASE_ERROR_DIR";

	// 요구수신용 디렉토리 프라퍼티 키 정보  20090921 add by dhjeong
	public static final String REQUEST_RCV_DIR_INFO   = "RequestRcvDirInfo";
	public static final String REQUEST_RCV_ROOT_DIR   = "req.root.directory";
	public static final String REQUEST_RCV_ERROR_DIR  = "req.error.directory";


	private static String getBatchDir(String propGroupKey, String propKey) throws Exception {
		String batchDir = PropManager.getInstance().getProperty(propGroupKey, propKey);
		if (batchDir == null) {
			if (propGroupKey.equals(REQUEST_SND_DIR_INFO)) {
//				if      (propKey.equals(REQUEST_SND_REAL_DIR  )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "REAL" }));  //배치 {1} {2} 디렉토리 정보를 프라퍼티에서 찾을 수 없습니다.
//				else if (propKey.equals(REQUEST_SND_ROOT_DIR  )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ROOT" }));
//				else 
				if (propKey.equals(REQUEST_SND_ARCH_DIR  )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ARCH" }));
				else if (propKey.equals(REQUEST_SND_ERROR_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ERROR"}));

			} else if (propGroupKey.equals(RESPONSE_RCV_DIR_INFO)) {
				if      (propKey.equals(RESPONSE_RCV_REAL_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "REAL" }));
				else if (propKey.equals(RESPONSE_RCV_ROOT_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ROOT" }));
				else if (propKey.equals(RESPONSE_RCV_ARCH_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ARCH" }));
				else if (propKey.equals(RESPONSE_RCV_ERROR_DIR)) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ERROR"}));
//				else if (propKey.equals(RESPONSE_RCV_NAS_DIR))   throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "NAS"}));
//				else if (propKey.equals(RESPONSE_RCV_CHK_DIR))   throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "CHECK"}));

//			} else if (propGroupKey.equals(RESPONSE_SND_DIR_INFO)) {
//				if      (propKey.equals(RESPONSE_SND_REAL_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"응답송신", "REAL" }));
//				else if (propKey.equals(RESPONSE_SND_ARCH_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"응답송신", "ARCH" }));
			}

			//add by dhjeong at 2009.09.21
			else if (propGroupKey.equals(REQUEST_RCV_DIR_INFO)) {
				if      (propKey.equals(REQUEST_RCV_ROOT_DIR  ))  throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"요구수신", "ROOT" }));  //배치 {1} {2} 디렉토리 정보를 프라퍼티에서 찾을 수 없습니다.
				else if (propKey.equals(REQUEST_RCV_ERROR_DIR  )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"요구수신", "ERROR" }));
			}
		}
		//디렉토리 맨끝에 "/" 가 있으면 빼고 리턴
		return batchDir.endsWith("/")? batchDir.substring(0, batchDir.length()-1) : batchDir;
	}

//	public static String getRequestRealDir() throws Exception {
//		return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_REAL_DIR);
//	}
//
//	public static String getRequestRootDir() throws Exception {
//		return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_DIR);
//	}

	public static String getRequestArchDir() throws Exception {
		return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ARCH_DIR);
	}

	public static String getRequestErrorDir() throws Exception {
		return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ERROR_DIR);
	}

	public static String getResponseRealDir() throws Exception {
		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_REAL_DIR);
	}

	public static String getResponseRootDir() throws Exception {
		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ROOT_DIR);
	}

	public static String getResponseArchDir() throws Exception {
		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ARCH_DIR);
	}

	public static String getResponseErrorDir() throws Exception {
		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ERROR_DIR);
	}

////	add by dhjeong at 2012.10.17
//	public static String getResponseNasDir() throws Exception {
//		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_NAS_DIR);
//	}
//
////	add by dhjeong at 2012.10.17
//	public static String getResponseChkDir() throws Exception {
//		return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_CHK_DIR);
//	}

//	public static String getResSendRealDir() throws Exception {
//		return getBatchDir(RESPONSE_SND_DIR_INFO, RESPONSE_SND_REAL_DIR);
//	}
//
//	public static String getResSendArchDir() throws Exception {
//		return getBatchDir(RESPONSE_SND_DIR_INFO, RESPONSE_SND_ARCH_DIR);
//	}

//	add by dhjeong at 2009.09.21
	public static String getReqRecvRootDir() throws Exception {
		return getBatchDir(REQUEST_RCV_DIR_INFO, REQUEST_RCV_ROOT_DIR);
	}

	public static String getReqRecvErrorDir() throws Exception {
		return getBatchDir(REQUEST_RCV_DIR_INFO, REQUEST_RCV_ERROR_DIR);
	}
	public static String getRequestRootExt(){
		String defaultExt = ".chk"; 
		try {
			String ext = getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_EXT);
			if ( ext == null )
				ext = defaultExt;
			return ext;
		} catch (Exception e) {
			return defaultExt;
		}
	}
	public static String getResponseRootExt(){
		String defaultExt = ".chk"; 
		try {
			String ext = getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ROOT_EXT);
			if ( ext == null )
				ext = defaultExt;
			return ext;
		} catch (Exception e) {
			return defaultExt;
		}
	}
	
	/**
	 * snd 디렉토리
	 * @return
	 * @throws Exception
	 */
	public static String getRequestRootDir() throws Exception {
		return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_DIR);
	}
	
}
