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

import com.eactive.eai.adapter.wca.exception.WCAException;
import com.eactive.eai.adapter.wca.global.WCADefine;
import com.eactive.eai.adapter.wca.jdbc.CommonJDBC;
import com.eactive.eai.adapter.wca.jdbc.JDBCFactory;
import com.eactive.eai.adapter.wca.jdbc.SQLData;
import com.eactive.eai.adapter.wca.servlet.TableInfoEx;
import com.eactive.eai.common.util.Logger;

import java.util.HashMap;
import java.util.Iterator;

public class SNAAgentUtil {
    static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    static Logger trc_logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
    /**
     * SNAAdapter critical한 정보 로깅을 위한 logger 
     */
    static Logger adapter_logger = Logger.getLogger(WCADefine.ADAPTER_LOGGER_NAME);
    
    /** 
    * 1. 기능 : Softlink 전체 설정 정보 디시 로드
    * 2. 처리 개요 : 
    *       - 프로퍼티 정보에서 softlink 홈디렉토리 get하여 명령어 수행 (SnaUpdateCfg -a)
    *       - 에러 발생시 그 메세지를 exception으로 발생시킨다.
    * 3. 주의사항 
    *
    * @exception    WCAException
    **/
    public static void notifyAllSoftlinkNode() throws WCAException
    {
//        String 		sResult;
        HashMap		nodes = null;
        String		sSoftLinkHome = null;
        try
        {
        	nodes = getAllSoftlinkNodeInfo();
        	if(nodes == null) {
        		logger.info("notifyAllSoftlinkNode> getAllSoftlinkNodeInfo Return NULL, So Return");
        		return;
        	}
        	
        	sSoftLinkHome = getSoftLinkHome();
        	logger.info("notifyAllSoftlinkNode> SoftLink Home = " + sSoftLinkHome);
        	
        	if(nodes.isEmpty() == true) {
        		logger.info("notifyAllSoftlinkNode> SoftLink Node Info HashMap is Empty, So Return");
        		return;
        	}
        	
        	Iterator it = nodes.keySet().iterator();        	
        	
            String svrName = "";
            String svrIP = "";

            while(it.hasNext()){
                svrName = (String)it.next();
                svrIP = (String) nodes.get(svrName);
                
                try {
                	/*
		 	        if(adapter_logger.isWarn()) 
			        	adapter_logger.warn("notifyAllSoftlinkNode> Notify : " + svrName + ", " + svrIP);
			        */
            		logger.info("notifyAllSoftlinkNode> Notify : " + svrName + ", " + svrIP);                	
		 	        
                	RuntimeUtil.getInstance().notifyAllSoftlink(sSoftLinkHome, svrIP);
                } 
                catch (Exception e) {
                    logger.info("SNAAgentUtil] broadcast Excpetion - " + svrName + "(" + svrIP + ") : "+ e.toString());
                    /*
                    logger.error("SNAAgentUtil] broadcast Excpetion - "+svrName + "(" + svrIP + ") : "+ e.toString());                    
		 	        if(adapter_logger.isWarn()) 
			        	adapter_logger.warn("notifyAllSoftlinkNode> Notify : " + svrName + ", " + svrIP + ", Msg = " + e.toString());
			        */                    
                }
            }                    	
        }
        catch(WCAException e) {
        	logger.info("notifyAllSoftlinkNode> Exception Msg = " + e.toString());
//            e.printStackTrace();
            /*            
            WCAException exception = new WCAException();
            exception.setMessage(e.toString());

 	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("notifyAllSoftlinkNode> Exception Msg = " + e.toString());
            throw exception;
            */
        }
        catch(Exception e) {
        	logger.info("notifyAllSoftlinkNode> Exception Msg = " + e.toString());            	
//            e.printStackTrace();
            /*
            WCAException exception = new WCAException();
            exception.setMessage(e.toString());
 	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("notifyAllSoftlinkNode> Exception Msg = " + e.toString());            
            throw exception;
            */
        }        
    }
	
    /** 
     * 1. 기능 : Softlink 전체 설정 정보 디시 로드
     * 2. 처리 개요 : 
     *       - 프로퍼티 정보에서 softlink 홈디렉토리 get하여 명령어 수행 (SnaUpdateCfg -a)
     *       - 에러 발생시 그 메세지를 exception으로 발생시킨다.
     * 3. 주의사항 
     *
     * @exception    WCAException
     **/
     public static void notifySoftlinkNode(String sHostName) throws WCAException
     {
//         String 		sResult;
         HashMap		nodes = null;
         String		sSoftLinkHome = null;
         try
         {
         	nodes = getSoftlinkNodeInfo(sHostName);
         	if(nodes == null) {
         		logger.info("notifySoftlinkNode> getAllSoftlinkNodeInfo Return NULL, So Return");
         		return;
         	}
         	
         	sSoftLinkHome = getSoftLinkHome();
         	logger.info("notifySoftlinkNode> SoftLink Home = " + sSoftLinkHome);
         	
         	if(nodes.isEmpty() == true) {
         		logger.info("notifySoftlinkNode> SoftLink Node Info HashMap is Empty, So Return");
         		return;
         	}
         	
         	Iterator it = nodes.keySet().iterator();        	
         	
             String svrName = "";
             String svrIP = "";

             while(it.hasNext()){
                 svrName = (String)it.next();
                 svrIP = (String) nodes.get(svrName);
                 
                 try {
                 	/*
 		 	        if(adapter_logger.isWarn()) 
 			        	adapter_logger.warn("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP);
 			        */
             		logger.info("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP);                	
 		 	        
                 	RuntimeUtil.getInstance().notifyAllSoftlink(sSoftLinkHome, svrIP);
                 } 
                 catch (Exception e) {
                	 logger.error("SNAAgentUtil] broadcast Excpetion - ", e);
                     logger.info("SNAAgentUtil] broadcast Excpetion - " + svrName + "(" + svrIP + ") : ");
                     /*
                     logger.error("SNAAgentUtil] broadcast Excpetion - "+svrName + "(" + svrIP + ") : "+ e.toString());                    
 		 	        if(adapter_logger.isWarn()) 
 			        	adapter_logger.warn("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP + ", Msg = " + e.toString());
 			        */                    
                 }
             }                    	
         }
         catch(WCAException e) {
         	logger.info("notifySoftlinkNode> Exception Msg = " + e.toString());
//             e.printStackTrace();
             /*            
             WCAException exception = new WCAException();
             exception.setMessage(e.toString());

  	        if(adapter_logger.isWarn()) 
 	        	adapter_logger.warn("notifySoftlinkNode> Exception Msg = " + e.toString());
             throw exception;
             */
         }
         catch(Exception e) {
         	logger.info("notifySoftlinkNode> Exception Msg = " + e.toString());            	
//             e.printStackTrace();
             /*
             WCAException exception = new WCAException();
             exception.setMessage(e.toString());
  	        if(adapter_logger.isWarn()) 
 	        	adapter_logger.warn("notifyAllSoftlinkNode> Exception Msg = " + e.toString());            
             throw exception;
             */
         }        
     }
     
     // 20080827 Start
     /** 
      * 1. 기능 : Softlink 전체 설정 정보 디시 로드
      * 2. 처리 개요 : 
      *       - 프로퍼티 정보에서 softlink 홈디렉토리 get하여 명령어 수행 (SnaUpdateCfg -a)
      *       - 에러 발생시 그 메세지를 exception으로 발생시킨다.
      * 3. 주의사항 
      *
      * @exception    WCAException
      **/
      public static void notifySoftlinkNode(String sHostName, String sAdapterGroupName, String sLuGroupName) throws WCAException
      {
//          String 		sResult;
          HashMap		nodes = null;
          String		sSoftLinkHome = null;
          try
          {
          	nodes = getSoftlinkNodeInfo(sHostName);
          	if(nodes == null) {
          		logger.info("notifySoftlinkNode> getAllSoftlinkNodeInfo Return NULL, So Return");
          		return;
          	}
          	
          	sSoftLinkHome = getSoftLinkHome();
          	logger.info("notifySoftlinkNode> SoftLink Home = " + sSoftLinkHome);
          	
          	if(nodes.isEmpty() == true) {
          		logger.info("notifySoftlinkNode> SoftLink Node Info HashMap is Empty, So Return");
          		return;
          	}
          	
          	Iterator it = nodes.keySet().iterator();        	
          	
              String svrName = "";
              String svrIP = "";

              while(it.hasNext()){
                  svrName = (String)it.next();
                  svrIP = (String) nodes.get(svrName);
                  
                  try {
                  	/*
  		 	        if(adapter_logger.isWarn()) 
  			        	adapter_logger.warn("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP);
  			        */
              		logger.info("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP);                	
  		 	        
                  	RuntimeUtil.getInstance().notifyAllSoftlink(sSoftLinkHome, svrIP, sAdapterGroupName, sLuGroupName);
                  } 
                  catch (Exception e) {
                      logger.info("SNAAgentUtil] broadcast Excpetion - " + svrName + "(" + svrIP + ") : "+ e.toString());
                      /*
                      logger.error("SNAAgentUtil] broadcast Excpetion - "+svrName + "(" + svrIP + ") : "+ e.toString());                    
  		 	        if(adapter_logger.isWarn()) 
  			        	adapter_logger.warn("notifySoftlinkNode> Notify : " + svrName + ", " + svrIP + ", Msg = " + e.toString());
  			        */                    
                  }
              }                    	
          }
          catch(WCAException e) {
          	logger.info("notifySoftlinkNode> Exception Msg = " + e.toString());
//              e.printStackTrace();
              /*            
              WCAException exception = new WCAException();
              exception.setMessage(e.toString());

   	        if(adapter_logger.isWarn()) 
  	        	adapter_logger.warn("notifySoftlinkNode> Exception Msg = " + e.toString());
              throw exception;
              */
          }
          catch(Exception e) {
          	logger.info("notifySoftlinkNode> Exception Msg = " + e.toString());            	
              /*
              WCAException exception = new WCAException();
              exception.setMessage(e.toString());
   	        if(adapter_logger.isWarn()) 
  	        	adapter_logger.warn("notifyAllSoftlinkNode> Exception Msg = " + e.toString());            
              throw exception;
              */
          }        
      }
      // 2080827 End 
     
    private static String getSoftLinkHome() throws Exception {
    	StringBuffer 	sbQuery = new StringBuffer();
        String 			sSoftLinkHome = "/fsapp/eai/SNAAdapter";    	
        try {    	
	        sbQuery.append( "SELECT PRPTY2VAL " + 
	                "   FROM " + TableInfoEx.T_LU_PROPS  + 
	                "   WHERE PRPTYGROUPNAME = '"+ TableInfoEx.T_SOFTLINK_PROP_GRP_NAME + "' AND " +
	                "   PRPTYNAME = 'softlink.home'");    	
	        
	        logger.info("getSoftLinkHome> Query =" + sbQuery.toString());
	        
	        JDBCFactory factory = JDBCFactory.newInstance();
	        CommonJDBC  common 	= (CommonJDBC)factory.create(CommonJDBC.class);
	        SQLData     data 	= common.select(sbQuery.toString());
	        
	        int nRsltCnt = 0;
	        if(data != null) {
	            nRsltCnt 		= data.getDispDatasCount();
	        }	 
	        logger.info("getSoftLinkHome> Record Count =" + nRsltCnt);	        
	        
	        if(nRsltCnt > 0) {	        
		        for(int nIndx = 0 ; nIndx < nRsltCnt; nIndx++) {	
		             sSoftLinkHome = data.getSQLStringData("PRPTY2VAL" + nIndx);				 
		             logger.info("getSoftLinkHome> Record : " + sSoftLinkHome);		             		 	        
		        }        
	        }
	        return sSoftLinkHome;
        }
        catch(Exception e) {
        	logger.info("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());        	
        	/*
 	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());
	        */        	
        	return sSoftLinkHome;
        }	        
    }
    
    private static HashMap getAllSoftlinkNodeInfo() throws Exception {
        HashMap 		nodes 	= new HashMap();   
        StringBuffer 	sbQuery = new StringBuffer();
        
        try {						
	        sbQuery.append( "select SNAADPTRSEVRNAME, SNAADPTRSEVRIPNAME, SNAADPTRSEVRCTNT " + 
	                "   FROM " + TableInfoEx.T_LU_HOST  + 
	                "   WHERE 1=1 ");
	        
	        /*
	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Query =" + sbQuery.toString());
	        */
	        logger.info("getAllSoftlinkNodeInfo> Query =" + sbQuery.toString());	        
	        
	        JDBCFactory factory = JDBCFactory.newInstance();
	        CommonJDBC  common 	= (CommonJDBC)factory.create(CommonJDBC.class);
	        SQLData     data 	= common.select(sbQuery.toString());
	        
	        int nRsltCnt = 0;
	        if(data != null) {
	            nRsltCnt 		= data.getDispDatasCount();
	        }
	        
	        /*
	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Record Count =" + nRsltCnt);
	        */
	        logger.info("getAllSoftlinkNodeInfo> Record Count =" + nRsltCnt);	        
	        
	        if(nRsltCnt > 0) {
		        String sSNAAdptrSevrName = "";
		        String sSNAAdptrSevrIPName = "";
		        
		        for(int nIndx = 0 ; nIndx < nRsltCnt; nIndx++)
		        {	
		             sSNAAdptrSevrName = data.getSQLStringData("SNAADPTRSEVRNAME" + nIndx);				 
		             sSNAAdptrSevrIPName = data.getSQLStringData("SNAADPTRSEVRIPNAME" + nIndx);				 
		             
		             /*
		 	         if(adapter_logger.isWarn()) 
			        	adapter_logger.warn("getAllSoftlinkNodeInfo> Record : " + sSNAAdptrSevrName + ", " + sSNAAdptrSevrIPName);
			        */
		             logger.info("getAllSoftlinkNodeInfo> Record : " + sSNAAdptrSevrName + ", " + sSNAAdptrSevrIPName);		             
		 	        
		             nodes.put(sSNAAdptrSevrName, sSNAAdptrSevrIPName);
		        }        
	        }
	        return nodes;
        }
        catch(Exception e) {
        	logger.info("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());        	
        	/*
 	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());
	        */        	
        	return null;
        }
    }
    
    private static HashMap getSoftlinkNodeInfo(String sHostName) throws Exception {
        HashMap 		nodes 	= new HashMap();   
        StringBuffer 	sbQuery = new StringBuffer();
        
        try {  
	        sbQuery.append( "SELECT SNAADPTRSEVRNAME, SNAADPTRSEVRIPNAME, SNAADPTRSEVRCTNT  " + 
	                "   FROM " + TableInfoEx.T_LU_HOST  + 
	                "   WHERE SNAADPTRSEVRNAME='" + sHostName + "' ");
	        
	        /*
	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Query =" + sbQuery.toString());
	        */
	        logger.info("getAllSoftlinkNodeInfo> Query =" + sbQuery.toString());	        
	        
	        JDBCFactory factory = JDBCFactory.newInstance();
	        CommonJDBC  common 	= (CommonJDBC)factory.create(CommonJDBC.class);
	        SQLData     data 	= common.select(sbQuery.toString());
	        
	        int nRsltCnt = 0;
	        if(data != null) {
	            nRsltCnt 		= data.getDispDatasCount();
	        }
	        
	        /*
	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Record Count =" + nRsltCnt);
	        */
	        logger.info("getAllSoftlinkNodeInfo> Record Count =" + nRsltCnt);	        
	        
	        if(nRsltCnt > 0) {
		        String sSNAAdptrSevrName = "";
		        String sSNAAdptrSevrIPName = "";
		        
		        for(int nIndx = 0 ; nIndx < nRsltCnt; nIndx++)
		        {	
		             sSNAAdptrSevrName = data.getSQLStringData("SNAADPTRSEVRNAME" + nIndx);				 
		             sSNAAdptrSevrIPName = data.getSQLStringData("SNAADPTRSEVRIPNAME" + nIndx);				 
		             
		             /*
		 	         if(adapter_logger.isWarn()) 
			        	adapter_logger.warn("getAllSoftlinkNodeInfo> Record : " + sSNAAdptrSevrName + ", " + sSNAAdptrSevrIPName);
			        */
		             logger.info("getAllSoftlinkNodeInfo> Record : " + sSNAAdptrSevrName + ", " + sSNAAdptrSevrIPName);		             
		 	        
		             nodes.put(sSNAAdptrSevrName, sSNAAdptrSevrIPName);
		        }        
	        }
	        return nodes;
        }
        catch(Exception e) {
        	logger.info("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());        	
        	/*
 	        if(adapter_logger.isWarn()) 
	        	adapter_logger.warn("getAllSoftlinkNodeInfo> Exception Msg = " + e.toString());
	        */        	
        	return null;
        }
    }    
}
