package com.eactive.eai.rms.onl.manage.serviceinfo.firstaccount;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.agent.firstaccount.RemoteFirstAccountCommand;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
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.onl.common.service.OnlAgentUtilServiceImpl;

@Service("firstAccountService")
public class FirstAccountService extends BaseService{
	
	private static final Logger logger = Logger.getLogger(FirstAccountService.class);
	
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
	@Autowired
	@Qualifier("onlAgentUtilService")
	private OnlAgentUtilServiceImpl onlAgentUtilService;
	
	 
	//file read
	public String accountChkMsg() throws Exception{
		
		String returnMsg = "";
		String txtFullPath = "";
		String txtFileNm = "";
		BufferedReader br = null;
		
		try{
			//파일 path 파일명 
			txtFullPath = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_PATH,"");
			txtFileNm = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_FILENM,"");
			txtFileNm = txtFullPath + txtFileNm;
			
			File dir = new File(txtFullPath);
			if (!dir.exists()) {
				throw new Exception("시스템 폴더를 찾을 수 없습니다. - "+ txtFullPath);
			}
			
			if(!"".equals(txtFileNm)){
				File FileName = new File(txtFileNm);
				br = new BufferedReader(new FileReader(FileName.getAbsolutePath()));
				StringBuffer sb = new StringBuffer();

				String lbuff = null;

				while ((lbuff = br.readLine())!= null) {
					sb.append(lbuff);
				}
				returnMsg = sb.toString();
			}
		}catch (Exception e){
			//returnMsg = "account txtFile read error. ";
			logger.error("account txtFile read error : "+e.getMessage());
		}finally {
			if(br != null) {
				try {
					br.close();
				}
				catch(Exception ex) {
					
				}
			}
		}	
		
		return returnMsg;
	}
	
	
	// Local File Write(WARNING or SAFETY) 이건 서버소켓에서만 함
	public void writeMsg(String msg) {
		BufferedWriter bw = null;
		String txtFullPath = "";
		String txtFileNm = "";
		try {
			//파일 path 파일명 
			txtFullPath = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_PATH,"");
			txtFileNm = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_FILENM,"");
			txtFileNm = txtFullPath + txtFileNm;
			
			File dir = new File(txtFullPath);
	    	if (!dir.exists()) {
	    		dir.mkdirs();
	    	}
	    	
			if(!"".equals(txtFileNm)){
				// 파일 path 파일명
				File fout = new File(txtFileNm);
				bw = new BufferedWriter(new FileWriter(fout, false));
				bw.write(msg);
			}
			
		} catch (Exception e) {
			logger.error("File write error" + e.getMessage());
		} finally {
			if (bw != null)
				try {
					bw.close();
				} catch (Exception ex) {

			}
		}
	}
	
	public int  syncWithFW(String msg) throws Exception{
		int result = 0;
		
		Map<String, Object> sendData = new HashMap<String, Object>();
		sendData.put("accNum", msg);
		
		String applyInstNm = monitoringContext.getStringProperty(MonitoringContext.FIRSTACCOUNT_INST,"");
		
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			DataSourceContextHolder.setDataSourceType(d);
			if("ISG".equals(d.getName())) continue;
			
			RemoteFirstAccountCommand command = new RemoteFirstAccountCommand();
			command.setArgs(sendData);
			//운영은 공동망만 적용
			if (!SystemUtil.isDevServer()){
				if(!"".equals(applyInstNm) && applyInstNm.equals(d.getName())){
					if(logger.isInfoEnabled()) logger.info("ProdServer apply inst : "+applyInstNm);
					if (!validate(onlAgentUtilService.broadcast(command))){  
			    		result = 1; 
			        	logger.error("broadcast failed");
			    	}
				}
				
			}else{
				if(logger.isInfoEnabled()) logger.info(" DevServer broadcast ");
				if (!validate(onlAgentUtilService.broadcast(command))){  
		    		result = 1; 
		        	logger.error("broadcast failed");
		    	}
			}
		
	    	
		    	
		}
		
		return result;
	}
	
	  private boolean validate(HashMap<String,Object> map ){
	    	for(String key : map.keySet()){
	    		Object o = map.get(key);
	    		
	    		if (o instanceof String){
	    			if("success".equals((String)o)){
	    				;
	    			}else{
	    				return false;
	    			}
	    		}else{
	    			return false;
	    		}
	    	}
	    	return true;
	    }
		
	
	


}
