package com.nms.server.thread.change.socket;

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.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
import com.nms.server.util.socket.SocketUtils;



/**
 * 变更通讯线程
 * 发送变更信息通讯
 * 线程返回值：
 * -3 命令参数为空
 * -2 通讯创建失败
 * -1 变更信息保存入库
 * 0  通讯成功并删除变更信息
 */

public class ChangeSocketThread  extends SocketUtils implements Callable<Object> {
	
	//日志组件对象
	private static Logger logger = Logger.getLogger(ChangeSocketThread.class);
	
	private String cmd;
	private Object obj;
	private Long recordId;
	public ChangeSocketThread(Long recordId,String ip, int port,String cmd,Object data) {
		super(ip, port);
		this.recordId = recordId;
		this.cmd = cmd;
		this.obj = data;
	}

	@Override
	public Object call(){
//		Thread.currentThread().setName("变更通讯 To:>"+ip);
		Thread.currentThread().setName("Change Communication To:>"+ip);
		try {
			
			createClientSocket();
			
			if(StringUtils.isEmpty(cmd)){
				return -3;
			}
			
			if(cmd.contains("char")){
				this.sendMessage(cmd);
				logger.debug("cmd:> "+cmd+" 发送命令结果>> "+this.receiveMessage());
				this.sendMessage(((JSONObject)obj).toString());
				logger.debug("cmd:> "+cmd+" 发送数据结果>> "+this.receiveMessage());
			}
			
			CommonDao dao = null;
			try {
				dao = new CommonDao();
				ChangeService service = new ChangeService(dao);
				if(recordId!=null){
					service.deleteEventRecordByIds(recordId.toString());
				}
			} catch (Exception e) {
				logger.error("Change record save failure", e);
			}finally{
				if(dao!=null){
					dao.close();
					dao=null;
				}
			}
			return 0;
		} catch (Exception e) {
			String errorInfo = "Target communication:>"+ip+" create failure："+e.getMessage();
			logger.error(errorInfo);
			//Common.addErrorInfo(EmailTypeConstants.ERROR_SOCKET, ip, new Date(), (long)EmailTypeConstants.STATE_FAIL, errorInfo);
			if(recordId==null){
				CommonDao dao = null;
				try {
					dao = new CommonDao();
					ChangeService service = new ChangeService(dao);
					if(SocketCMD.WEB_NOTICE_ACTIVE_ALARM_START_ALERT.equalsIgnoreCase(cmd)) {//对于NC节点是否报主动告警的变更保存，针对发给同一客户端（NC）的只保存一条，避免多次变更后，导致NC是否主动报警不是最新状态（因为采用的是多线程，所以不一定按时间先后）
						EventRecordLibrary event = service.selectEventRecordInfo("S2C", cmd, Common.getIpSeqIdMap().get(ip)+"");
						if (event!=null) {//更新
							service.updateEventRecordLibrary(event,DateUtil.getCurrentTime(),((JSONObject)obj).toString());
						}else {//新增
							service.saveEventRecordLibrary(cmd, Common.getIpSeqIdMap().get(ip)+"", "S2C", ((JSONObject)obj).toString());
						}
					}else {
						service.saveEventRecordLibrary(cmd, Common.getIpSeqIdMap().get(ip)+"", "S2C", ((JSONObject)obj).toString());
					}
				} catch (Exception e1) {
					logger.error("Change record save failure", e1);
					return -1;
				}finally{
					if(dao!=null){dao.close();dao = null;}
				}
			}
			return -2;
		}finally{
			close();
		}
	}
}