package com.nms.server.thread.dataCollect;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Map.Entry;

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

import com.nms.server.bean.MissionResult2;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;

/**
 * 任务（对于该有结果，而无结果的任务）结果收集线程
 *    DC发送要收集的命令
 *    Agent端发送任务结果
 *    
 * @author hyx
 * 
 */
public class NonRltTaskResultCollectThread extends SSLSocketCallable {
	Logger logger = Logger.getLogger(NonRltTaskResultCollectThread.class);
	private String name; // 自定义Thread Name
	private Map<String,String[]> taskInfoMap;//需要收集结果的任务id
	
	public NonRltTaskResultCollectThread(String name,String ip,Integer port,Map<String,String[]> taskInfoMap) throws Exception {
		super(ip,port);
		this.name = name;
		this.taskInfoMap = taskInfoMap;
	}

	/**与Client端进行通信：SSLSocketCallable已经握手过了
	 *  收集监测数据、任务结果、回传文件
	 */
	@Override
	protected Object toDo() throws Exception
	{
		// 为当前线程命名 ，用与开发阶段友好输出。
		Thread.currentThread().setName(name);
//		int zipTaskResult = 0;
//		int objTaskResult = 0;
		
		try {
//			//设置超时时间
			socket.setSoTimeout(100*1000);//如果放到String msg0 = receiveMessage();下面，会报错，socket closed
			//进行通信:SSLSocketCallable已经建立握手了
			sendMessage(SocketCMD.REQ_NONRLTTASK_RESULT_COLLECT);//DC：要进行任务结果收集
			String msg0 = receiveMessage();
			logger.info("任务（对于该有结果，而无结果的任务）结果收集，client端"+this.ip+"回应信息："+msg0);
			
			if(SUCCESS.equalsIgnoreCase(msg0)) {
				Iterator taskInfoIte = taskInfoMap.entrySet().iterator();
				while(taskInfoIte.hasNext()) {
					Entry enTask = (Entry)taskInfoIte.next();
					if(enTask!=null && enTask.getKey()!=null) {						
						String taskId = enTask.getKey().toString();
						String[] taskInfo = (String[])enTask.getValue();
						if(StringUtils.isNotBlank(taskInfo[2])) {
							logger.info("startTime="+taskInfo[2]);
							Long timeTmp=null;
							
							if(NumberUtils.isDigits(taskInfo[2])){
								timeTmp = Long.parseLong(taskInfo[2]);
							}else{
								timeTmp = DateUtil.toLongTime(taskInfo[2]);
							}
							
							taskInfo[2] = timeTmp==null?null:timeTmp.toString();
						}
						if(StringUtils.isNotBlank(taskInfo[3])) {
							logger.info("endTime="+taskInfo[3]);
							Long timeTmp3=null;
							
							if(NumberUtils.isDigits(taskInfo[2])){
								timeTmp3 = Long.parseLong(taskInfo[2]);
							}else{
								timeTmp3 = DateUtil.toLongTime(taskInfo[2]);
							}
							taskInfo[3] = timeTmp3==null?null:timeTmp3.toString();
						}
						String taskInfoStr = taskId+Constants.COMMON_DATA_POINT+
						taskInfo[0]+Constants.COMMON_DATA_POINT+
						taskInfo[1]+Constants.COMMON_DATA_POINT+
						(taskInfo[2]==null?"":taskInfo[2])+Constants.COMMON_DATA_POINT+//与NC协商好的，用""
						(taskInfo[3]==null?"":taskInfo[3]);
//					    System.out.println("向NC端发送的任务信息"+taskInfoStr);
						logger.info("DC向NC("+this.ip+")端发送的任务信息:"+taskInfoStr);
						this.sendMessage(taskInfoStr);
						
						msg0 = receiveMessage();
						if(StringUtils.isNotBlank(msg0)) {
//						System.out.println("NC端发送的结果信息"+msg0);
						logger.info("NC("+this.ip+")向DC端发送的结果信息:"+msg0);
						String [] result = msg0.split(Constants.COMMON_DATA_SPLIT);
//						logger.info("参数个数:"+result.length);
//						logger.info("结果:"+result[0]);
							if("1".equals(result[0])) {//如果失败，则将结果存入缓存列表，等待下次入库
								MissionResult2 result2 = new MissionResult2();
								result2.setMissionId(taskId==null?null:Long.parseLong(taskId));
								result2.setResult(1l);//不属于人工判定失败
								result2.setDescription(result[1]);
								result2.setStartTime(taskInfo[2]==null?null:Long.parseLong(taskInfo[2]));
								result2.setEndTime(taskInfo[3]==null?null:Long.parseLong(taskInfo[3]));
								result2.setLoopFlag(taskInfo[1]==null?null:Long.parseLong(taskInfo[1]));
								result2.setMissionType(taskInfo[0]==null?null:Long.parseLong(taskInfo[0]));						
								result2.setUuid(Common.getIpSeqIdMap().get(ip));
								Common.addResultToResultList(result2);	
								logger.info("存入缓存一条失败结果（NC("+this.ip+")端无任务"+taskId+"对应的结果,人工产生一条失败结果）");
							}						
						}
					}
				}	
				sendMessage(SocketCMD.COMMUNICATION_END);
			}
			
			logger.info("任务结果收集执行线程：与client端"+this.ip+"的通信结束");
			
		} catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		}
		return null;
	}
	
	public static void main(String[] args) {
		try
		{
//			new NonRltTaskResultCollectThread("数据收集执行线程","10.0.6.120",Constants.SSL_CLIENT_PORT,"1274605").call();
			
			//只处理绝对路径
			ResourceBundle log4jRb = ResourceBundle.getBundle("log4j");
			String logFile = log4jRb.getString("log4j.appender.logfile.File");
			File f = new File(logFile);
			if(f!=null&&f.isAbsolute()) {
				String logPath = f.getParent();
				System.out.println(logPath);
			}
//			System.out.println(f.getParent());//1.null  2.\*   3*
//			System.out.println(f.isAbsolute());//1.null  2.\*   3*
//			System.out.println(f.getParentFile().isDirectory());//1.null  2.\*   3*
//			System.out.println(f.getParentFile().getAbsolutePath());
//			String webPathTmp = NonRl/buildPath(webPathTmp.substring(1,webPathTmp.length()-16));
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
