package com.nms.server.thread.change;

import static com.nms.server.thread.socket.SocketCMD.SEND_PLUGIN_SCRIPT_FILE;

import java.util.List;
import java.util.concurrent.Callable;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.thread.ResetServerThread;
import com.nms.server.thread.change.socket.ChangeSocketThread;
import com.nms.server.thread.mission.LoadNewMissionThread;

public class ChangeThread implements Callable<Object>{
	Logger logger = Logger.getLogger(ChangeThread.class);
	ChangeService changeService = null;
	String name ;
	/**
	 * 监测设置信息变更请求命令（设置告警修改）
	 */
	private String WEB_NOTICE_SET_INFO_ALERT = "char:setInfoAlert";
	/**
	 * 节点或节点组状态变更请求命令：节点组id:节点id（缺省为0）
	 */
	private String WEB_NOTICE_NODE_AND_GROUP_STATE_ALERT = "char:nodeAndGroupAlert";
	/**
	 * 监测类别信息变更包括字段的变更（表结构改变）请求命令
	 */
	private String WEB_NOTICE_CHECK_TYPE_ALERT = "char:checkTypeIdAlert";
	/**
	 * 任务信息变更请求命令
	 */
	private String WEB_NOTICE_MISSION_INFO_ALERT = "char:missionInfoAlert";
	
	/**
	 * DC控制信息
	 */
	private String WEB_NOTICE_DATACONTROLLER = "char:Datacontroller";
	
	/**
	 * 节点是否报主动告警变更请求命令
	 */
	private String WEB_NOTICE_ACTIVE_ALARM_START_ALERT = "char:isActiveAlarmStart";
	
	public ChangeThread (String name){
		this.name = name;
	}
	
	@Override
	public Object call() throws Exception {
		Thread.currentThread().setName(name);
		CommonDao dao = null;
		try {
			dao = new CommonDao();
			final ChangeService service = new ChangeService(dao);
			List<EventRecordLibrary> mrlList = service.getNewEventRecordList();
			
			//工作数量对象(ipList.size()个工作数，阻塞当前线程执行，直至所有子线程完成执行)
//			CountDownLatch downLatch = new CountDownLatch(mrlList.size());
			
			 // 根据发送失败暂存信息，重新发送脚本文件
			 ChangePluginScriptFile.sendPluginFileBaseOnEventRecord(mrlList);	
				
			 StringBuffer ids = new StringBuffer();
			 
			 if(mrlList != null && mrlList.size()>0){
				 for (final EventRecordLibrary record : mrlList) {
					 boolean delFlag = false;
					 try {
						 
						 //-- WEB TO SERVER 通讯,当DC查询了W2S的记录后，就代表web和DC通信成功了，剩下的就是DC和NC的通信了
						 if("W2S".equals(record.getRecordType())){
							 if(WEB_NOTICE_SET_INFO_ALERT.equals(record.getRecordCommand())){
								Common.service.submit(new ChangeForSetInfo(record.getId(),record.getRecordContent()));
							 }else if(WEB_NOTICE_NODE_AND_GROUP_STATE_ALERT.equals(record.getRecordCommand())){
								 
								 String datas = record.getRecordContent();
								 String []  data = datas.split(":");
								 Common.service.submit(new ChangeForNodeGroup(record.getId(),data)); 
								 
							 }else if(WEB_NOTICE_CHECK_TYPE_ALERT.equals(record.getRecordCommand())){
								 
								 String datas = record.getRecordContent();
								 String []  data = datas.split(":");
								 Common.service.submit(new ChangeForCheckType(record.getId(),data));
							 }else if(WEB_NOTICE_MISSION_INFO_ALERT.equals(record.getRecordCommand())){//新增任务
								 
								 String datas = record.getRecordContent();
								 String []  data = datas.split(":");
								 if(StringUtils.isNotEmpty(data[0])){
									 Common.service.submit(new LoadNewMissionThread(Long.parseLong(data[0]) ));
								 }
								 delFlag = true;
							 }else if(WEB_NOTICE_DATACONTROLLER.equals(record.getRecordCommand())){
								 
								 String datas = record.getRecordContent();
								 if(StringUtils.isNotEmpty(datas)){
									 Common.service.submit(new ResetServerThread(Integer.parseInt(datas) ));
								 }
								 delFlag = true;
							 }else if(WEB_NOTICE_ACTIVE_ALARM_START_ALERT.equals(record.getRecordCommand())){//NC是否报主动告警
								//5秒后执行下发:否则多次更改状态时，可能不一定按设置的先后时间来
								 Thread.sleep(5000);
								 String datas = record.getRecordContent();
								 if(StringUtils.isNotEmpty(datas)){
									 Common.service.submit(new ChangeForActiveAlarmInfo(record.getId(),record.getRecordContent()));
								 }
								 delFlag = true;
							} else {

								// -- 无法判断直接删除
								delFlag = true;
							}
						 }
						 
						 //-- SERVER TO CLIENT 通讯 针对于单节点的通信  监测设置的变更 节点状态的有效无效
						 else if("S2C".equals(record.getRecordType())){
							 if(SEND_PLUGIN_SCRIPT_FILE.equals(record.getRecordCommand())) {
								 // 第三方检测脚本下发通过ChangePluginScriptFile.sendPluginFileBaseOnEventRecord实现
								 continue;
								 
							 } else {
								 if(record.getSeqId()!=null && record.getSeqId().longValue()!=0l){
									 String ip = Common.getNodeIpByUUID(record.getSeqId());
									 Common.runChangeRunnable(
											 new ChangeSocketThread(record.getId(),ip, 
													 Constants.SSL_CLIENT_PORT,
													 record.getRecordCommand(),
													 JSONObject.fromObject(record.getRecordContent()))
					                 );
								 }
							 }
						 }
						 
					} catch (NumberFormatException e) {
						logger.error("", e);
					}
					if(delFlag)ids.append(",'"+record.getId()+"'");
				}
				 
				if(ids.length() > 0){
					ids.deleteCharAt(0);
					logger.debug("待删除的 recordid" + ids);
					service.deleteEventRecordByIds(ids.toString());
				}
			 }
		} catch (Exception e) {
			logger.error("Change operation exception", e);
		}finally{
			if(dao!=null){
				dao.close();
				dao=null;
			}
		}
		
		return null;
	}

/*	public static void p(Object ss){
		System.out.print(ss==null?null:ss.toString());
	}
	public static void pl(Object ss){
		System.out.println(ss==null?null:ss.toString());
	}*/
}
