package com.eactive.eai.rms.onl.common.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.onl.dashboard.service.Dashboard2RepositoryService;
import com.eactive.eai.rms.onl.tracking.vo.MemStaticsVo;


public class ItsmDashboardTransReportJob implements Job{

	/**
	 * Logger
	 */
	private static final Logger logger = Logger.getLogger(ItsmDashboardTransReportJob.class);
    
    
    @Autowired
    @Qualifier("dashboard2RepositoryService")
    private Dashboard2RepositoryService dashboard2Repository;
    
    @Autowired
    @Qualifier("eaiServerInfoService")    
    private EaiServerInfoService eaiServerInfoService;
    
    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
    	
    	if(logger.isInfoEnabled()) logger.info("START ItsmDashboardTransReportJob");

   		ApplicationContext appContext = null;
   		try {
   			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
   			dashboard2Repository = (Dashboard2RepositoryService)appContext.getBean("dashboard2RepositoryService");
   			eaiServerInfoService = (EaiServerInfoService)appContext.getBean("eaiServerInfoService");
   			
   		} catch (SchedulerException e) {
   			logger.error("applicationContext get module error",e);
   			return ;
   		}  
   		
   		try{
   			
   			HashMap<String, MemStaticsVo> memStaticsVos = new HashMap<String, MemStaticsVo>();
   			
   			
   			for(DataSourceType dataSourceType : DataSourceTypeManager.getOnlineDataSourceTypes()){
   				List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>> ();
   				DataSourceContextHolder.setDataSourceType(dataSourceType);
   				String typeName = dataSourceType.getName();
   				memStaticsVos.put(typeName, dashboard2Repository.getMemTradeVoByService(typeName));
   				
   				List<Map<String, String>> list = eaiServerInfoService.getEaiServerIpListDB();
   				if( list != null ) {
                	for( Map<String,String> map : list ) {
                		HashMap<String,Object> tempMap = new HashMap<String,Object>();
                		String host = map.get("HOSTNAME");
                		String inst = map.get("EAISVRINSTNM");
                		MemStaticsVo mvo = dashboard2Repository.getMemTradeVo(host, inst) ;
                		tempMap.put("host", host);
                		tempMap.put("inst", inst);
        				tempMap.put("procTotal", mvo.getProcTotal());
        				data.add(tempMap);
                	}
   				
   				}
   				
   				//if(logger.isInfoEnabled()) logger.info("data :" + data );
   				
   				//각 서버 인스턴스별 거래건수 
   	   			HashMap<String,HashMap<String,Object>> resultMap = new HashMap<String,HashMap<String,Object>> ();
   				for(int i=0;i<data.size();i++){
   					
   					String hostNm = data.get(i).get("host").toString();
   					if(resultMap.containsKey(hostNm)){
   						resultMap.get(hostNm).put("procTotal", Integer.parseInt(resultMap.get(hostNm).get("procTotal").toString())
   														+Integer.parseInt(data.get(i).get("procTotal").toString()));
   					}else{
   						resultMap.put(hostNm, data.get(i));
   					}
   					
   				}
   				
   				HashMap<String,String> instMap = new HashMap<String,String>();
   				Iterator<String> it = resultMap.keySet().iterator();
   				String instKey = "";
				int idx = 0;
   				while( it.hasNext() ) {
   					String key = it.next();
   					HashMap tmpMap = resultMap.get(key);
   					instKey = (String)tmpMap.get("inst");
   					idx = instKey.indexOf("_");
   					instKey = (!"".equals(instKey)?instKey.substring(instKey.length()-1):key);
   					instMap.put(instKey, String.valueOf(tmpMap.get("procTotal")));
   				}
   				if(logger.isDebugEnabled()) logger.debug("typeName :" + typeName + " ,instMap : " +instMap.toString());
   				
   				dashboard2Repository.setItsmDashServerInstTotalProcMap(typeName,instMap);
   			}
   			
   			//일괄전송
   			HashMap<String,String> etcMap = new HashMap<String,String>();
        	String isgProc = dashboard2Repository.getProcBatch();
        	String tmpProc[] = isgProc.split(",");
        	int isgProcSum = 0 ;
        	if( tmpProc.length > 1 ) {
        		int send = CommonUtil.getInt(tmpProc[0]);
        		int recv = CommonUtil.getInt(tmpProc[1]);
        		isgProcSum = send + recv ;
        	}
        	etcMap.put("1", String.valueOf(isgProcSum));
        	dashboard2Repository.setItsmDashServerInstTotalProcMap("ISG",etcMap);
   			
   			
   			for (String key : memStaticsVos.keySet()) {
   				HashMap tmp = new HashMap();
   				MemStaticsVo memStaticsVo = memStaticsVos.get(key);
   				
   				//스케줄러 메모리에 있는 총 건수 확인
   				HashMap<String,String> preMap = new HashMap<String,String>();
   				preMap = dashboard2Repository.getItsmDashTranInfo(key);
   	   			
   				int preProcTotal = 0;    //이전거래건수
   				int preErrorTotal = 0;    //이전업무에러건수
   				int preSysErrorTotal = 0;    //이전통신에러건수
   				
   				//증가치
   				int procTotalIncr = 0;   
   				int errorTotalIncr = 0;
   				int sysErrorTotalIncr = 0;
   				
   				if(preMap != null){
   					preProcTotal = Integer.parseInt(String.valueOf(preMap.get("preProcTotal")));
   					preErrorTotal = Integer.parseInt(String.valueOf(preMap.get("preErrorTotal")));
   					preSysErrorTotal = Integer.parseInt(String.valueOf(preMap.get("preSysErrorTotal")));
   				}
   				
   				//if(logger.isDebugEnabled()) logger.debug("이전 거래건수 : "+ preProcTotal + " ,이전업무에러건수 : "+ preErrorTotal + " ,이전통신에러건수 : "+ preSysErrorTotal);
   				
   				//업무그룹  거래처리 거래처리증가 타임아웃 업무에러 업무에러증가 통신에러 통신에러증가
   				//group text 저장
   				String typeText = "";
   				
   				DataSourceType dt = DataSourceTypeManager.getDataSourceType((String) key);
   				
   				if(dt != null){
   					typeText = dt.getName();
   				}
   				
   				tmp.put("group",typeText);
   				tmp.put("procTotal",memStaticsVo.getProcTotal());
   				tmp.put("timeoutTotal",memStaticsVo.getTimeoutTotal());
   				tmp.put("errorTotal",memStaticsVo.getErrorTotal());
   				tmp.put("syserrorTotal",memStaticsVo.getSysErrorTotal());
   				
   				if(preProcTotal > 0){  //이전거래건수 있을경우 값 비교
   					if((int)memStaticsVo.getProcTotal() > 0) procTotalIncr = (int)memStaticsVo.getProcTotal() - preProcTotal;
   				}
   				
   				if(preErrorTotal > 0){  //이전거래건수 있을경우 값 비교
   					if((int)memStaticsVo.getErrorTotal() > 0) errorTotalIncr = (int)memStaticsVo.getErrorTotal() - preErrorTotal;
   				}
   				
   				if(preSysErrorTotal > 0){  //이전거래건수 있을경우 값 비교
   					if((int)memStaticsVo.getSysErrorTotal() > 0) sysErrorTotalIncr = (int)memStaticsVo.getSysErrorTotal() - preSysErrorTotal;
   				}
   				//if(logger.isDebugEnabled()) logger.debug("거래건수 증가치 : "+ procTotalIncr + " ,업무에러건수 증가치: "+ errorTotalIncr + " ,통신에러건수 증가치 : "+ sysErrorTotalIncr);
   				
   				tmp.put("procTotalIncr",String.valueOf(procTotalIncr));
   				tmp.put("errorTotalIncr",String.valueOf(errorTotalIncr));
   				tmp.put("syserrorTotalIncr",String.valueOf(sysErrorTotalIncr));
   				//이전값 갱신
   				tmp.put("preProcTotal",memStaticsVo.getProcTotal());
   				tmp.put("preErrorTotal",memStaticsVo.getErrorTotal());
   				tmp.put("preSysErrorTotal",memStaticsVo.getSysErrorTotal());
   				
   				if(logger.isDebugEnabled()) logger.debug("메모리 save : "+ tmp.toString());
   				
   				dashboard2Repository.setItsmDashTranInfo((String) key, tmp);
   				
   			}
   			
   			//일괄
    		String batchCount = dashboard2Repository.getProcBatch();
    		dashboard2Repository.setItsmDashTranInfoBatch(batchCount);
    		
			//배치
    		String batchCount2 = dashboard2Repository.getProcEaiBatch();
    		dashboard2Repository.setItsmDashTranInfoBatch2(batchCount2);
   			
   			if(logger.isInfoEnabled()) logger.info("END ItsmDashboardTransReportJob");
   			
   		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("ItsmDashboardTransReportJob error : ",e);
		}
		
				
   	}
	
	
}
