package com.eactive.eai.adapter.wca.cfg;

import com.eactive.eai.adapter.wca.global.WCADefine;
import com.eactive.eai.adapter.wca.jdbc.BaseJDBC;
import com.eactive.eai.adapter.wca.jdbc.JDBCException;
import com.eactive.eai.adapter.wca.util.DateUtil;
import com.eactive.eai.common.util.Logger;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

/** 
* 1. 기능 : LU 그룹 정보 테이블을 접근하기 위한 JDBC 클래스
* 2. 처리 개요 :
* 3. 주의사항 
*
* @author  :  
* @version : v 1.0.0
* @see     : SessionGroupQuery.java
* @since   : 
*/
public class SessionGroupJDBCEx extends BaseJDBC implements SessionGroupQueryEx
{     
    /**
     * SNAAdapter 트레이스 로깅을 위한 logger 
     */
    Logger trc_logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
    
    // 20080827 Start
    /**
     * SNAAdapter critical한 정보 로깅을 위한 logger 
     */
    Logger adapter_logger = Logger.getLogger(WCADefine.ADAPTER_LOGGER_NAME);
    // 20080827 End
    
    // 20080827 Start
    /** 
     * 1. 기능 :  Softlink IP 주소에 해당하는 노드 이름을 구한다.
     * 2. 처리 개요
     * 3. 주의사항 
     *
     * @params       softlinkIpAddr      Softlink IP 주소
     * 
     * @return       Softlink 노드 이름
     * 
     * @exception    JDBCException       DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
     **/
     public String getSoftlinkNodeName(String softlinkIpAddr) throws JDBCException {
         ResultSet 	rs = null;
         String		softlinkNodeName = "";
         
         try {
             getDsConnection();
             
             if(adapter_logger.isInfo()) 
            	 adapter_logger.info("getSoftlinkNodeName> Query = " + GET_SOFTLINK_NODE_NAME);  
             
             setStatement(GET_SOFTLINK_NODE_NAME);
             
             this.preparedStatement.setString(1, softlinkIpAddr);
             
             rs = executeSelect();
                       
             while (rs.next()) {
            	 softlinkNodeName = rs.getString(1);
            	 adapter_logger.info("getSoftlinkNodeName> softlinkNodeName = " + softlinkNodeName);              	 
             }
             
             return softlinkNodeName;
             
         } 
         catch (Exception e) {
             if(adapter_logger.isError()) { 
            	 adapter_logger.error("getSoftlinkNodeName> Exception Occur, Msg", e);
             }
             throw new JDBCException("SessionGroupJDBC","getSoftlinkNodeName",e);
         } 
         finally {
        	 try {
        		 if (rs != null) { rs.close(); }
        	 }
        	 catch(Exception ex) {}
             this.close();
         }
     }
     // 20080827 End
     
    /** 
     * 1. 기능 : Softlink 노드 이름에 해당하는 시스템의 IP 주소를 구한다.
     * 2. 처리 개요
     * 3. 주의사항 
     *
     * @params       softlinkNodeName    Softlink 노드 이름
     * 
     * @return       Softlink IP 주소
     * 
     * @exception    JDBCException       DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함) 
     **/
    public String getSoftlinkIpAddr(String softlinkNodeName) throws JDBCException {
        ResultSet 	rs = null;
        String		softlinkIpAddr = "";
          
        try {
        	getDsConnection();
              
            if (adapter_logger.isInfo()) { 
             	 adapter_logger.info("getSoftlinkIpAddr> Query = " + GET_SOFTLINK_IP_ADDR);
            }
              
            setStatement(GET_SOFTLINK_IP_ADDR);
              
            this.preparedStatement.setString(1, softlinkNodeName);
              
            rs = executeSelect();
                        
            while (rs.next()) {
            	softlinkIpAddr = rs.getString(1);
             	adapter_logger.info("getSoftlinkNodeName> softlinkNodeName = " + softlinkNodeName);              	 
            }
              
            return softlinkIpAddr;
        } 
        catch (Exception e) {
        	adapter_logger.error("getSoftlinkIpAddr> Exception Occur, Msg", e);            
            throw new JDBCException("SessionGroupJDBC", "getSoftlinkIpAddr", e);
        } 
        finally {
			try {
				if (rs != null) {
					rs.close();
				}
			} 
			catch (Exception ex) { }
            this.close();
        }
    }
    // 20080827 End     
     
    /** 
    * 1. 기능 :  노드, 어댑터 그룹 이름에 해당하는 모든 LU 그룹 정보 반환
    * 2. 처리 개요 : 검색된 LU 그룹 정보를 SessionGroupData Object 저장한다.
    * 3. 주의사항 
    *
    * @params       nodeName            노드 이름
    * @params       adapterGroupName    어댑터 그룹 이름
    * @return       HashMap             노드, 어댑터 그룹 이름에 해당하는 모든 LU 그룹 정보를 저장한다.
    * @exception    JDBCException       DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
    **/
    // 20090228 Start
    // 20080827 Start
    // public HashMap getAdapterInfo(String nodeName, String adapterGroupName) throws JDBCException {
    // public HashMap getAdapterInfo(String nodeName, String nodeIpAddr, String adapterGroupName) throws JDBCException {
    // 20080827 End
     public HashMap getAdapterInfo(HashMap luGroupInfoMap, String nodeName, String nodeIpAddr, 
    		 					   String adapterGroupName, String sStartBackupSession, boolean bBackupSessionEnableFlag) throws JDBCException {     
    // 20090228 End
        ResultSet rs = null;
        
        try {
            getDsConnection();
            setStatement(GET_ADAPTER);
            this.preparedStatement.setString(1, nodeName);
            this.preparedStatement.setString(2, adapterGroupName);
            rs = executeSelect();
            
            SessionGroupDataEx    info      = null;            
            
            while (rs.next()) {
                info = new SessionGroupDataEx(rs.getString(1), rs.getString(2));	// 어댑터 기동 서버명 및 어댑터 그룹 이름 값 설정
                info.setGroupName(rs.getString(3));									// LU 그룹 설정
                info.setPort(rs.getString(4));
                info.setSessionCnt(rs.getString(5));
                info.setBackupCvsMode(rs.getString(6));
                info.setBackupNodeName(rs.getString(7));
                info.setBackupPort(rs.getString(8));
                info.setBackupCvsVal(rs.getString(9));
                info.setLogYN(rs.getString(10));
                info.setLogLevel(rs.getString(11));
                info.setLogSize(rs.getString(12));
                info.setTranTimeout(rs.getString(13));    
                
                // 20080827 Start
                // info.setSoftLinkSevrName(rs.getString(14));
                info.setSoftLinkSevrName(nodeIpAddr);
                // info.setSoftLinkSevrName("127.0.0.1");		// For 임시 테스트
                // 20080827 End
                
                // 20090228 Start
                info.setStartBackupSession(sStartBackupSession);
                // 20090228 End
                
                // 20090810 Start
                info.setBackupEnableFlag(bBackupSessionEnableFlag);
                // 20090810 End
                
                if (trc_logger.isDebug()){
                    trc_logger.debug("==================================================");
                    trc_logger.debug("getAdapterInfo] " + info.toString());
                    trc_logger.debug("==================================================");
                }
                
                // 2008.09.09 Start
                if (adapter_logger.isWarn()) { 
                 	adapter_logger.warn("getAdapterInfo> " + info.toString());
                 	adapter_logger.warn("getAdapterInfo> Add Session Info To " + info.getGroupName());
                }
                // 2008.09.09 End

                // 20090810 Start
                // LU 그룹 값을 키로 하여 LU 그룹 세션 정보 저장 
                // sessgroups.put(info.getGroupName(), info);
                luGroupInfoMap.put(info.getGroupName(), info);
                // 20090810 End
            }
            
            return luGroupInfoMap;
            
        } 
        catch (Exception e) {
            adapter_logger.error("getAdapterInfo error", e);
            throw new JDBCException("SessionGroupJDBC","getAdapterInfo",e);
        } 
        finally {
        	try {
				if (rs != null) {
					rs.close();
				}
			} 
        	catch (Exception ex) { }
            this.close();
        }
    }
  
    
   /** 
    * 1. 기능 :  LU 그룹 정보 등록 및 해당하는 LU 정보 수정
    * 2. 처리 개요 : 
    * 3. 주의사항 
    *
    * @param        data    SessionGroupData Object
    * @return       추가된 레코드 수 
    * @exception    JDBCException   DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
    **/
    public int insertSessionGroup(SessionGroupDataEx data) throws JDBCException {
        int nExeCnt = 0;
        try {
            DateUtil dateUtil = new DateUtil();
            String sDateTime = dateUtil.getDateMilliTime();
            getDsConnection();
            setAutoCommit(false);
            setStatement(INSERT_SESSION_GROUP); 
            this.preparedStatement.setString(1,data.getNodeName());
            this.preparedStatement.setString(2,data.getAdapterGroupName());
            this.preparedStatement.setString(3,data.getGroupName());
            this.preparedStatement.setInt(4,data.getPort());
            this.preparedStatement.setInt(5,data.getSessionCnt());
            this.preparedStatement.setInt(6,data.getTranTimeout());
            this.preparedStatement.setInt(7,data.getDummyOffset());
            this.preparedStatement.setInt(8,data.getHostSndRUSize());
            this.preparedStatement.setInt(9,data.getHostRcvRUSize());
            this.preparedStatement.setString(10,data.getApplyID());
            
            this.preparedStatement.setString(11,data.getBackupCvsMode());
            this.preparedStatement.setInt(12,data.getBackupCvsVal());
            this.preparedStatement.setString(13,data.getBackupNodeName());
            this.preparedStatement.setInt(14,data.getBackupPort());
            
            this.preparedStatement.setString(15,data.getLogYN());
            this.preparedStatement.setString(16,data.getStringLogLevel());
            this.preparedStatement.setInt(17,data.getLogSize());
            
            this.preparedStatement.setString(18, sDateTime);
            this.preparedStatement.setString(19, sDateTime);
            
            // 20080827 Start
            // 20080527 Start
            // this.preparedStatement.setString(20, data.getSoftLinkSevrName());
            // 20080527 End
            // 20080827 End 
            
            nExeCnt =executeUpdate();
            
            setStatement(UPDATE_LU_INFO);
            this.preparedStatement.setString(1,data.getApplyID());
            this.preparedStatement.setString(2,data.getLogYN());
            this.preparedStatement.setString(3,data.getStringLogLevel());
            this.preparedStatement.setInt(4,data.getLogSize());
            this.preparedStatement.setString(5,sDateTime);   
            this.preparedStatement.setString(6,data.getNodeName());
            this.preparedStatement.setString(7,data.getAdapterGroupName());
            this.preparedStatement.setString(8,data.getGroupName());                   
            nExeCnt += executeUpdate();
            commit();
            return nExeCnt;
        } 
        catch (SQLException e) {
            throw new JDBCException("SessionGroupJDBC","insertSessionGroup",e);
        } 
        finally {
            this.close();   
        }
    }
    
    /** 
    * 1. 기능 :  LU 그룹 정보 삭제
    * 2. 처리 개요 : 
    * 3. 주의사항 
    *
    * @param        data    SessionGroupData Object
    * @return       삭제된 레코드 수 
    * @exception    JDBCException   DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
    **/
    public int deleteSessionGroup(SessionGroupDataEx vo) throws JDBCException {
        int nExeCnt = 0;
        try {            
            getDsConnection();
            setStatement(DELETE_SESSION_GROUP); 
            this.preparedStatement.setString(1,vo.getNodeName());
            this.preparedStatement.setString(2,vo.getAdapterGroupName());
            this.preparedStatement.setString(3,vo.getGroupName());            
            nExeCnt = executeUpdate();
            return nExeCnt;
        } 
        catch (SQLException e) {
            throw new JDBCException("SessionGroupJDBC","deleteSessionGroup",e);
        } 
        finally {
            this.close();   
        }
    }
    
    /** 
    * 1. 기능 : LU 그룹 정보와 LU 그룹에 해당하느 LU 정보 삭제
    * 2. 처리 개요 : 
    * 3. 주의사항 
    *
    * @param        data    SessionGroupData Object
    * @return       삭제된 레코드 수 
    * @exception    JDBCException   DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
    **/
    public int deleteAllSessionGroup(SessionGroupDataEx vo) throws JDBCException {
        int nExeCnt = 0;
        try {            
            getDsConnection();
            setAutoCommit(false);
            
            setStatement(DELETE_SESSION_GROUP); 
            this.preparedStatement.setString(1,vo.getNodeName());
            this.preparedStatement.setString(2,vo.getAdapterGroupName());
            this.preparedStatement.setString(3,vo.getGroupName());            
            nExeCnt = executeUpdate();
            
            setStatement(DELETE_ALL_LU_INFO);
            this.preparedStatement.setString(1,vo.getNodeName());
            this.preparedStatement.setString(2,vo.getAdapterGroupName());
            this.preparedStatement.setString(3,vo.getGroupName());
            nExeCnt += executeUpdate();
            
            commit();
            return nExeCnt;
        } 
        catch (SQLException e) {
            throw new JDBCException("SessionGroupJDBC","deleteAllSessionGroup",e);
        } 
        finally {
            this.close();   
        }
    }
   
   /** 
    * 1. 기능 :  LU 그룹 정보 및 해당하는 LU 정보 수정
    * 2. 처리 개요 : 
    * 3. 주의사항 
    *
    * @param        data    SessionGroupData Object
    * @return       수정된 레코드 수 
    * @exception    JDBCException   DB 작업시 발행하는 예외 발생 정보 (SQLException 에러코드와 메세지 포함)
    **/
    public int updateSessionGroup(SessionGroupDataEx data) throws JDBCException {
        int nExeCnt = 0;
        try {
            DateUtil dateUtil = new DateUtil();
            
            getDsConnection();
            setAutoCommit(false);
            // 세션 그룹 update
            setStatement(UPDATE_SESSION_GROUP);        
            this.preparedStatement.setInt(1,data.getPort());
            this.preparedStatement.setInt(2,data.getSessionCnt());
            this.preparedStatement.setInt(3,data.getTranTimeout());
            this.preparedStatement.setInt(4,data.getDummyOffset());
            this.preparedStatement.setInt(5,data.getHostSndRUSize());
            this.preparedStatement.setInt(6,data.getHostRcvRUSize());
            this.preparedStatement.setString(7,data.getApplyID());
            
            this.preparedStatement.setString(8,data.getBackupCvsMode());
            this.preparedStatement.setInt(9,data.getBackupCvsVal());
            this.preparedStatement.setString(10,data.getBackupNodeName());
            this.preparedStatement.setInt(11,data.getBackupPort());
            
            this.preparedStatement.setString(12,data.getLogYN());
            this.preparedStatement.setString(13,data.getStringLogLevel());
            this.preparedStatement.setInt(14,data.getLogSize());
            
            this.preparedStatement.setString(15, dateUtil.getDateMilliTime());
            
            // 20080827 Start
            // 20080527 Start
            /*
            this.preparedStatement.setString(16,data.getNodeName());
            this.preparedStatement.setString(17,data.getAdapterGroupName());
            this.preparedStatement.setString(18,data.getGroupName());
            */
            /*
            this.preparedStatement.setString(16,data.getSoftLinkSevrName());
            this.preparedStatement.setString(17,data.getNodeName());
            this.preparedStatement.setString(18,data.getAdapterGroupName());
            this.preparedStatement.setString(19,data.getGroupName());
            */
            // 20080527 End
            this.preparedStatement.setString(16,data.getNodeName());
            this.preparedStatement.setString(17,data.getAdapterGroupName());
            this.preparedStatement.setString(18,data.getGroupName());            
            // 20080827 End
            
            nExeCnt = executeUpdate();

            // 20090227 Start            
            // LU applcation id & LU 로그 update
            /*
            setStatement(UPDATE_LU_INFO);
            this.preparedStatement.setString(1,data.getApplyID());
            this.preparedStatement.setString(2,data.getLogYN());
            this.preparedStatement.setString(3,data.getStringLogLevel());
            this.preparedStatement.setInt(4,data.getLogSize());
            this.preparedStatement.setString(5,dateUtil.getDateMilliTime());   
            this.preparedStatement.setString(6,data.getNodeName());
            this.preparedStatement.setString(7,data.getAdapterGroupName());
            this.preparedStatement.setString(8,data.getGroupName());                   
            */            
            if (data.getUpdateLuApplyID().compareTo("1") == 0) {
                setStatement(UPDATE_LU_INFO);
                this.preparedStatement.setString(1,data.getApplyID());
                this.preparedStatement.setString(2,data.getLogYN());
                this.preparedStatement.setString(3,data.getStringLogLevel());
                this.preparedStatement.setInt(4,data.getLogSize());
                this.preparedStatement.setString(5,dateUtil.getDateMilliTime());   
                this.preparedStatement.setString(6,data.getNodeName());
                this.preparedStatement.setString(7,data.getAdapterGroupName());
                this.preparedStatement.setString(8,data.getGroupName());
            }            
            else {
                setStatement(UPDATE_LU_INFO_EXCEPT_APPL_ID);
                this.preparedStatement.setString(1,data.getLogYN());
                this.preparedStatement.setString(2,data.getStringLogLevel());
                this.preparedStatement.setInt(3,data.getLogSize());
                this.preparedStatement.setString(4,dateUtil.getDateMilliTime());   
                this.preparedStatement.setString(5,data.getNodeName());
                this.preparedStatement.setString(6,data.getAdapterGroupName());
                this.preparedStatement.setString(7,data.getGroupName());            	
            }
            // 20090227 End
            nExeCnt += executeUpdate();
            commit();
            return nExeCnt;
        } 
        catch (SQLException e) {
            adapter_logger.error("updateSessionGroup error", e);
            throw new JDBCException("SessionGroupJDBC","updateSessionGroup",e);
        } 
        finally {
            this.close();   
        }
    }
}

