package com.eactive.eai.inbound.remote;

import java.sql.ResultSet;
import java.util.ArrayList;

import org.slf4j.LoggerFactory;

import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class RemoteServerDAO extends BaseDAO implements RemoteServerQuery
{

	public RemoteServerDAO() {
		super();
		super.logger = Logger.getLogger(Logger.LOGGER_FILEEVENT);
	}

	//-------------------------------------------------------------------------------------------
	// EAI <-> REMOTE 파일 자동 전송시 업무구분에 의한 Remote 서버정보 조회
	//-------------------------------------------------------------------------------------------
	public RemoteServerVO getRemoteServerByPath(String remotePath) throws DAOException {

		ResultSet rs = null;
//		int index    = 0;
		String bjobBzwkDstcd= null;

        try {
			String query = SELECT_REMOTE_SERVER_BY_PATH;
            this.connect(query);
//			logger.debug(">>> 업무구분에 의한 리모트 서버 조회 SQL : \n"+ query);

//			index = 1;
            //this.preparedStatement.setString(index++, remotePath);	logger.debug(">>> 바인드("+(index-1)+") : ["+ remotePath +"]");

            rs = executeQuery();

			RemoteServerVO info = null;
            while (rs.next()) {
            	bjobBzwkDstcd = StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd"  ));
            	if (remotePath.indexOf(bjobBzwkDstcd) == -1 )
            		continue;

                info = new RemoteServerVO();
                info.setRemoteServerId  (StringUtil.nvlTrim(rs.getString("RmtSevrID"  )));   // 리모트서버 ID (PK)
                info.setRemoteServerName(StringUtil.nvlTrim(rs.getString("RmtSevrName")));   // 리모트서버 명
                info.setProcessCode     (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd"     )));   // 업무구분코드 (FK)
                info.setRemoteServerIP  (StringUtil.nvlTrim(rs.getString("RmtSevrIP"  )));   // 리모트서버 IP
                info.setRemoteNdmPort   (StringUtil.nvlTrim(rs.getString("RmtSevrNDMPortNoName"   )));   // 리모트서버 NDM Port Number
                info.setRemoteFtpPort   (StringUtil.nvlTrim(rs.getString("RmtSevrFTPPortNoName"   )));   // 리모트서버 FTP Port Number
                info.setRemoteUserId    (StringUtil.nvlTrim(rs.getString("RmtSevrFTPUID"    )));   // 리모트서버 FTP User ID
                info.setRemotePassword  (StringUtil.nvl    (rs.getString("RmtSevrFTPUserPwdName"   )));   // 리모트서버 FTP User Password
                info.setRemoteRootDir   (StringUtil.nvlTrim(rs.getString("RmtSevrRootDirName"   )));   // 리모트서버 Root Directory
                info.setAutoTransferType(StringUtil.nvlTrim(rs.getString("RmtFileEvntCpyDstcd")));   // 리포트 파일 이벤트시 파일 복사 방법
                info.setUseYn           (StringUtil.nvlTrim(rs.getString("ThisMsgUseYn"      )));   // 사용여부
                info.setCreateId        (StringUtil.nvlTrim(rs.getString("ThisMsgRegsntID"   )));   // 등록자ID
                info.setCreateTime      (StringUtil.nvlTrim(rs.getString("ThisMsgRegiHMS"    )));   // 등록시간
                info.setUpdateId        (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID"    )));   // 수정자ID
                info.setUpdateTime      (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS"    )));   // 수정시간

				//리모트 Root Directory 가 "/" 로 끝나면 "/" 제거
				if (info.getRemoteRootDir().endsWith("/")) {
					info.setRemoteRootDir(info.getRemoteRootDir().substring(0, info.getRemoteRootDir().length()-1));
				}
            }
			//logger.info(">>> 업무구분에 의한 리모트 서버 조회 RemoteServerVO : "+ info);
            return info;

 		} catch (DAOException ex) {
			throw ex;
        } catch (Exception e) {
			String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {});
			throw new DAOException(errMsg);	//<--------------
        } finally {
            disconnect();
        }
    }




	//-------------------------------------------------------------------------------------------
	// REMOTE 서버정보 목록 검색 및 상세조회
	//-------------------------------------------------------------------------------------------
	public ArrayList<RemoteServerVO> selectRemoteServer(String searchProcessCode, String searchType, String searchText) throws DAOException {

		ResultSet rs = null;
		int index    = 0;

        try {
			String query = SEARCH_REMOTE_SERVER;
			
			if("SERVER_NAME".equals(searchType)) {
				query = query + " AND A.\"RmtSevrName\" LIKE '%" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" ";
			}
			else if("SERVER_ID".equals(searchType)) {
				query = query + " AND A.\"RmtSevrID\" LIKE '" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" ";
			}
			else if("SERVER_IP".equals(searchType)) {
				query = query + " AND A.\"RmtSevrIP\" LIKE '%" + searchText + "%'\n ORDER BY A.\"RmtSevrID\" ";
			}
			else {
				query = query + " ORDER BY A.\"RmtSevrID\" ";
			}
			
			
            this.connect(query);
			logger.debug(">>> 리모트 서버 검색 SQL : \n"+ query);

			index = 1;
            this.preparedStatement.setString(index++, searchProcessCode);	logger.debug(">>> 바인드("+(index-1)+") : ["+ searchProcessCode +"]");
			
            rs = executeQuery();

			ArrayList<RemoteServerVO> alist = new ArrayList<RemoteServerVO>();
			while (rs.next()) {
                RemoteServerVO info = new RemoteServerVO();
                info.setRemoteServerId  (StringUtil.nvlTrim(rs.getString("RmtSevrID"            )));   // 리모트서버 ID (PK)
                info.setRemoteServerName(StringUtil.nvlTrim(rs.getString("RmtSevrName"          )));   // 리모트서버 명
                info.setProcessCode     (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd"        )));   // 업무구분코드 (FK)
                info.setProcessName     (StringUtil.nvlTrim(rs.getString("BjobBzwkName"         )));   // 업무구분명
                info.setRemoteServerIP  (StringUtil.nvlTrim(rs.getString("RmtSevrIP"            )));   // 리모트서버 IP
                info.setRemoteNdmPort   (StringUtil.nvlTrim(rs.getString("RmtSevrNDMPortNoName" )));   // 리모트서버 NDM Port Number
                info.setRemoteFtpPort   (StringUtil.nvlTrim(rs.getString("RmtSevrFTPPortNoName" )));   // 리모트서버 FTP Port Number
                info.setRemoteUserId    (StringUtil.nvlTrim(rs.getString("RmtSevrFTPUID"        )));   // 리모트서버 FTP User ID
                info.setRemotePassword  (StringUtil.nvl    (rs.getString("RmtSevrFTPUserPwdName")));   // 리모트서버 FTP User Password
                info.setRemoteRootDir   (StringUtil.nvlTrim(rs.getString("RmtSevrRootDirName"   )));   // 리모트서버 Root Directory
                info.setAutoTransferType(StringUtil.nvlTrim(rs.getString("RmtFileEvntCpyDstcd"  )));   // 리포트 파일 이벤트시 파일 복사 방법
                info.setUseYn           (StringUtil.nvlTrim(rs.getString("ThisMsgUseYn"         )));   // 사용여부
                info.setCreateId        (StringUtil.nvlTrim(rs.getString("ThisMsgRegsntID"      )));   // 등록자ID
                info.setCreateTime      (StringUtil.nvlTrim(rs.getString("ThisMsgRegiHMS"       )));   // 등록시간
                info.setUpdateId        (StringUtil.nvlTrim(rs.getString("ThisMsgAmndrID"       )));   // 수정자ID
                info.setUpdateTime      (StringUtil.nvlTrim(rs.getString("ThisMsgAmndHMS"       )));   // 수정시간

				//리모트 Root Directory 가 "/" 로 끝나면 "/" 제거
				if (info.getRemoteRootDir().endsWith("/")) {
					info.setRemoteRootDir(info.getRemoteRootDir().substring(0, info.getRemoteRootDir().length()-1));
				}
				alist.add(info);
            }
			logger.info(">>> 리모트 서버 검색 건수 : "+ alist.size());
            return alist;

 		} catch (DAOException ex) {
			throw ex;
        } catch (Exception e) {
			String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {});
			throw new DAOException(errMsg);	//<--------------
        } finally {
            disconnect();
        }
    }

	//-------------------------------------------------------------------------------------------
	// REMOTE 서버정보 신규
	//-------------------------------------------------------------------------------------------
	public int insertRemoteServer(RemoteServerVO remoteServerVO) throws DAOException {

		int retValue = 0;
		int index    = 0;

		try {

			String query = INSERT_REMOTE_SERVER;
            this.connect(query);
			logger.debug(">>> 리모트 서버 등록 SQL : \n"+ query);

			index = 1;
			this.preparedStatement.setString(index++, remoteServerVO.getProcessCode     ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode     () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerName());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerName() +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getProcessCode     ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode     () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerIP  ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerIP  () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteNdmPort   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteNdmPort   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteFtpPort   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteFtpPort   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteUserId    ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteUserId    () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemotePassword  ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemotePassword  () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteRootDir   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteRootDir   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getAutoTransferType());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getAutoTransferType() +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUseYn           ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUseYn           () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getCreateId        ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getCreateId        () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getCreateTime      ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getCreateTime      () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUpdateId        ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateId        () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUpdateTime      ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateTime      () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getProcessCode     ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode     () +"]");

			retValue = this.executeUpdate();
			logger.info(">>> 리모트 서버 등록 건수 : "+ retValue);

			return retValue;

		} catch (DAOException ex) {
			throw ex;
		} catch (Exception e) {
			String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {});
			throw new DAOException(errMsg);	//<--------------
		} finally {
			disconnect();
		}
	}


	//-------------------------------------------------------------------------------------------
	// REMOTE 서버정보 변경
	//-------------------------------------------------------------------------------------------
	public int updatetRemoteServer(RemoteServerVO remoteServerVO) throws DAOException {

		int retValue = 0;
		int index    = 0;

		try {

			String query = UPDATE_REMOTE_SERVER;
            this.connect(query);
			logger.debug(">>> 리모트 서버 변경 SQL : \n"+ query);

			index = 1;
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerName());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerName() +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getProcessCode     ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getProcessCode     () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerIP  ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerIP  () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteNdmPort   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteNdmPort   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteFtpPort   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteFtpPort   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteUserId    ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteUserId    () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemotePassword  ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemotePassword  () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteRootDir   ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteRootDir   () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getAutoTransferType());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getAutoTransferType() +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUseYn           ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUseYn           () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUpdateId        ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateId        () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getUpdateTime      ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getUpdateTime      () +"]");
			this.preparedStatement.setString(index++, remoteServerVO.getRemoteServerId  ());	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerVO.getRemoteServerId  () +"]");

			retValue = this.executeUpdate();
			logger.info(">>> 리모트 서버 수정 건수 : "+ retValue);

			return retValue;

		} catch (DAOException ex) {
			throw ex;
		} catch (Exception e) {
			String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {});
			throw new DAOException(errMsg);	//<--------------
		} finally {
			disconnect();
		}
	}


	//-------------------------------------------------------------------------------------------
	// REMOTE 서버정보 삭제
	//-------------------------------------------------------------------------------------------
	public int deleteRemoteServer(String remoteServerId) throws DAOException {

		int retValue = 0;
		int index    = 0;

		try {

			String query = DELETE_REMOTE_SERVER;
            this.connect(query);
			logger.debug(">>> 리모트 서버 삭제 SQL : \n"+ query);

			index = 1;
			this.preparedStatement.setString(index++, remoteServerId);	logger.debug(">>> 바인드("+(index-1)+") : ["+ remoteServerId +"]");

			retValue = this.executeUpdate();
			logger.info(">>> 리모트 서버 삭제 건수 : "+ retValue);

			return retValue;

		} catch (DAOException ex) {
			throw ex;
		} catch (Exception e) {
			String errMsg = ExceptionUtil.getErrorCode(e, "UNDEFINEDCD", new String[] {});
			throw new DAOException(errMsg);	//<--------------
		} finally {
			disconnect();
		}
	}

}
