/**
 * 
 */
package com.eactive.eai.rms.client.agent;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.rms.client.SocketClient;
import com.eactive.eai.rms.client.dao.AgentAdapterDAO;
import com.eactive.eai.rms.onl.vo.AdaptersVO;

/**
 * @author cyyun
 * 
 */
public class AdaptersAgent extends AbstractScheduledAgent {

	private SocketClient socketClient;
	private final int maxBufferSize = 1024*3;					//어뎁터 모니터링 maxBufferSize 이상이면 모니터링 하지 않음 UDP Buffer 문제
	private AgentAdapterDAO agentAdapterDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		AdaptersVO adaptersVO = (AdaptersVO) applicationContext.getBean("adaptersVO");
		initAdapter( adaptersVO );
		checkAdapter( adaptersVO );		

		socketClient.send(adaptersVO);
		
		logger.debug("SEND AdaptersAgent : " + adaptersVO );
	}

	public void setSocketClient(SocketClient socketClient) {
		this.socketClient = socketClient;
	}
	public void setAgentAdapterDao(AgentAdapterDAO agentAdapterDao){
		this.agentAdapterDao = agentAdapterDao;
	}

	public AdaptersVO getAdapterInfo() {
		AdaptersVO adapter = new AdaptersVO();

		initAdapter(adapter);
		checkAdapter(adapter);

		return adapter;
	}

	
	@SuppressWarnings("unchecked")
    public void initAdapter(AdaptersVO adapter) {
		// get Adapter manager
		AdapterManager manager = AdapterManager.getInstance();

		// get Adapter group list
		HashMap voMap = manager.getAllAdapterGroupVO();

		Iterator it = voMap.keySet().iterator();

		String[] groupNames = new String[voMap.size()];

		for (int i = 0; it.hasNext(); i++) {
			groupNames[i] = (String) it.next();
		}

		Arrays.sort(groupNames);
		
		//송신하는 서버의 정보
		EAIServerManager serManager = EAIServerManager.getInstance();
		String localServName = serManager.getLocalServerName();
		adapter.setDisconAdaptersGroup(localServName);
		
	    //------------------------------------------
	    // 어뎁터 검색 조건에 의해 모니터링 제외 대상을 산정 - 2012.06.14 Edited by Chaesh
	    //------------------------------------------
	    HashMap monitorDisableMap = new HashMap();
	    try {
	    	monitorDisableMap = agentAdapterDao.getMonitorUseNoAdapterList();
	    }
	    catch(Exception ex) {
	    	logger.error("adapterMonitorPage.jsp - getMonitorUseAdapterList AdapterGroup Select Error. Skip ");
	    }
	    //------------------------------------------
	    // 시간 조건에 의해 모니터링 제외 대상을 산정 - 2012.06.14 Edited by Chaesh
	    //------------------------------------------
	    HashMap monitorTimeConditionMap = new HashMap();
	    try {
	    	monitorTimeConditionMap = agentAdapterDao.getMonitorTimeConditionAdapterList();
	    }
	    catch(Exception ex) {
	    	logger.error("adapterMonitorPage.jsp - getMonitorUseAdapterList AdapterGroup Select Error. Skip ");
	    }
	    //------------------------------------------
	    
	    Calendar cal = Calendar.getInstance();
	    int weekCount = cal.get(Calendar.DAY_OF_WEEK);
	    
	    // 20190214 dhlee
	    // BugFix : 11시 1분의 경우 : 111   -> 1101
//	    String timeCtnt = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)) + String.valueOf(cal.get(Calendar.MINUTE));
	    
		String timeCtnt = String.format("%02d",cal.get(Calendar.HOUR_OF_DAY)) 
				+ String.format("%02d", cal.get(Calendar.MINUTE));

		for (int i = 0; i < groupNames.length; i++) {

			// get Adapter group value
			AdapterGroupVO gvo = manager.getAdapterGroupVO(groupNames[i]);
			Iterator it2 = null;

			//------------------------------------------
		    // 모니터링 제외 N 어댑터 SKIP. - 2012.06.14
		    //------------------------------------------
			if(monitorDisableMap !=null && monitorDisableMap.size() > 0) {
				if(monitorDisableMap.get(groupNames[i]) != null) {
					continue;
				}
			}
			//------------------------------------------
		    // 모니터링 시간 조건 체크 - 2012.06.14
		    //------------------------------------------
			if(monitorTimeConditionMap !=null && monitorTimeConditionMap.size() > 0) {
				String conditionString = (String) monitorTimeConditionMap.get(groupNames[i]);
				if(	conditionString != null) {
					try {
						String[] ctntTemp = conditionString.split(",");
						if ( ctntTemp[0].equals("Y") ) {
							if ( ctntTemp[2].compareTo(timeCtnt) > 0 || ctntTemp[3].compareTo(timeCtnt) < 0) {
								continue;
							}
							if ( ctntTemp[1].equals("WEEKDAY") ) {
								switch ( weekCount ) {
									case 1 :
									case 7 :
										continue;
									default :
										;
								}
							}
						}
					} catch (Exception e){
						logger.error("Monitoring codition code parse Error - Plz check the rule.",e);
					}
				}
			}
			//------------------------------------------
			
			if (gvo == null)
				continue;

			// get Adapter list
			it2 = gvo.getAdapters();

			for (int j = 0; it2.hasNext(); j++) {

				// get Adapter value
				AdapterVO vo = (AdapterVO) it2.next();

				if (vo == null)
					continue;

				// total
				adapter.total[0]++;
				if (vo.isStarted())
					adapter.total[1]++;
				else
					adapter.total[2]++;

				if (("SNA").equals(gvo.getType())) {
					adapter.sna[0]++;
					if (vo.isStatus())
						adapter.sna[1]++;
					else
						adapter.sna[2]++;
				} else if (("SOC").equals(gvo.getType())) {
					adapter.socket[0]++;
					if (vo.isStatus())
						adapter.socket[1]++;
					else
						adapter.socket[2]++;
				} else if (("NET").equals(gvo.getType())) {
					adapter.socket2[0]++;

					if (vo.isStatus())
						adapter.socket2[1]++;
					else {
						adapter.socket2[2]++;
						//Status 가 false 상태은 어뎁터는 , 로 엮어서 RMS에 송신	
						if ( adapter.getDisconAdaptersGroup().length() < maxBufferSize )
							adapter.setDisconAdaptersGroup(adapter.getDisconAdaptersGroup() + "," + vo.getAdapterGroupName());
					}
				} else if (("WTC").equals(gvo.getType())) {
					adapter.tuxedo[0]++;
					if (vo.isStatus())
						adapter.tuxedo[1]++;
					else
						adapter.tuxedo[2]++;
				} else if (("IMQ").equals(gvo.getType())) {
					adapter.mq[0]++;
					if (vo.isStatus())
						adapter.mq[1]++;
					else
						adapter.mq[2]++;
				} else if (("HTT").equals(gvo.getType()) || ("RST").equals(gvo.getType())) {
					adapter.http[0]++;
					if (vo.isStatus())
						adapter.http[1]++;
					else
						adapter.http[2]++;
				} else if (("EJB").equals(gvo.getType())) {
					adapter.ejb[0]++;
					if (vo.isStatus())
						adapter.ejb[1]++;
					else
						adapter.ejb[2]++;
				}

			} // end of for(j)

		} // end of for(i)		
	}

	public void checkAdapter(AdaptersVO adapter) {

		if ((adapter.sna[0] == 0) || (adapter.sna[1] == 0))
			adapter.sna[3] = 0;
		else if ((adapter.sna[2] == 0))
			adapter.sna[3] = 2;
		else if ((adapter.sna[2] > 0))
			adapter.sna[3] = 1;

		// SOCKET
		if ((adapter.socket[0] == 0) || (adapter.socket[1] == 0))
			adapter.socket[3] = 0;
		else if ((adapter.socket[2] == 0))
			adapter.socket[3] = 2;
		else if ((adapter.socket[2] > 0))
			adapter.socket[3] = 1;

		// SOCKET2
		if ((adapter.socket2[0] == 0) || (adapter.socket2[1] == 0))
			adapter.socket2[3] = 0;
		else if ((adapter.socket2[2] == 0))
			adapter.socket2[3] = 2;
		else if ((adapter.socket2[2] > 0))
			adapter.socket2[3] = 1;

		// TUXEDO
		if ((adapter.tuxedo[0] == 0) || (adapter.tuxedo[1] == 0))
			adapter.tuxedo[3] = 0;
		else if ((adapter.tuxedo[2] == 0))
			adapter.tuxedo[3] = 2;
		else if ((adapter.tuxedo[2] > 0))
			adapter.tuxedo[3] = 1;

		// MQseries
		if ((adapter.mq[0] == 0) || (adapter.mq[1] == 0))
			adapter.mq[3] = 0;
		else if ((adapter.mq[2] == 0))
			adapter.mq[3] = 2;
		else if ((adapter.mq[2] > 0))
			adapter.mq[3] = 1;

		// HTTP
		if ((adapter.http[0] == 0) || (adapter.http[1] == 0))
			adapter.http[3] = 0;
		else if ((adapter.http[2] == 0))
			adapter.http[3] = 2;
		else if ((adapter.http[2] > 0))
			adapter.http[3] = 1;

		// EJB
		if ((adapter.ejb[0] == 0) || (adapter.ejb[1] == 0))
			adapter.ejb[3] = 0;
		else if ((adapter.ejb[2] == 0))
			adapter.ejb[3] = 2;
		else if ((adapter.ejb[2] > 0))
			adapter.ejb[3] = 1;

		// TOTAL
		// 1. 에러가 포함되었으면 => 에러
		// 2. 부분정상 이 포함되었으면 => 부분정상
		// 3. 전체 정상 이면 => 전체정상
		if (adapter.sna[3] == 0 || adapter.socket[3] == 0
				|| adapter.socket2[3] == 0 || adapter.tuxedo[3] == 0
				|| adapter.mq[3] == 0 || adapter.http[3] == 0
				|| adapter.ejb[3] == 0) {
			adapter.total[3] = 0;
		} else if (adapter.sna[3] == 1 || adapter.socket[3] == 1
				|| adapter.socket2[3] == 1 || adapter.tuxedo[3] == 1
				|| adapter.mq[3] == 1 || adapter.http[3] == 1
				|| adapter.ejb[3] == 1) {
			adapter.total[3] = 1;
		} else {
			adapter.total[3] = 2;
		}
		
		//--------------------------------------
		// 등록된 어댑터가 없는 경우 3으로 설정
		//--------------------------------------
		if(adapter.sna     [0] == 0 ) adapter.sna[3]      = 3 ;   
		if(adapter.socket  [0] == 0 ) adapter.socket[3]   = 3 ;
		if(adapter.socket2 [0] == 0 ) adapter.socket2[3]  = 3 ;
		if(adapter.mq      [0] == 0 ) adapter.mq[3]       = 3 ;
		if(adapter.http    [0] == 0 ) adapter.http[3]     = 3 ;
		if(adapter.ejb     [0] == 0 ) adapter.ejb[3]      = 3 ;
		if(adapter.tuxedo  [0] == 0 ) adapter.tuxedo[3]   = 3 ;
		//--------------------------------------
	}
	
	
	
	
//	private HashMap getDisabledAdapterList() throws Exception {
//		Connection conn = null;
//		Statement stmt = null;
//		ResultSet rs = null;
//		HashMap<String,String> disabledMap = new HashMap<String,String>();
//		
//		StringBuffer sb_sql = new StringBuffer();
//	
//		sb_sql.append(" select AdptrBzwkGroupName, EAISevrDstcd \n");
//		sb_sql.append(" from "+ Keys.TABLE_OWNER + "TSEAIAD01 \n");
//		sb_sql.append(" where EAISevrDstcd IN ( '6', '7', '8', '9' ) \n");
//	
//		try	{			
//			conn = getConnection();
//			stmt = conn.createStatement();
//	  		stmt.execute(sb_sql.toString());
//	  		rs = stmt.getResultSet();
//	  		
//	  		
//	  		while(rs.next()) {
//	  			disabledMap.put(rs.getString(1),rs.getString(2));
//			}               
//
//		return disabledMap;
//		}
//		catch(Exception e) {
//			logger.error(e);
//			throw e;
//		}
//		finally {
//			try {
//				if(rs != null)	 rs.close();
//				if(stmt != null) stmt.close();
//				if(conn != null) conn.close();
//			}
//			catch (SQLException sqle) {
//				logger.error("SQLException was thrown: " + sqle.getMessage(),sqle);
//			}
//		}
//	}
	


	
//	public static void main(String[] args) {
//		Calendar cal = Calendar.getInstance();
//	    int weekCount = cal.get(Calendar.DAY_OF_WEEK);
//		String timeCtnt = String.format("%02d",cal.get(Calendar.HOUR_OF_DAY)) 
//				+ String.format("%02d", cal.get(Calendar.MINUTE));
//		
//		String timeCtnt2 = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)) + String.valueOf(cal.get(Calendar.MINUTE));
//		
//		System.out.println(weekCount);
//		System.out.println(timeCtnt);
//		System.out.println(timeCtnt2);
//	}
}
