package com.nms.server.thread.mission;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task6;
import com.nms.server.common.Constants;
import com.nms.server.util.socket.SSLSocketCallable;
import com.socket.utils.FileComment;

public class NMSClientTask6 extends SSLSocketCallable{
	private final Logger logger = Logger.getLogger(NMSClientTask6.class);
	private Task6 task6 ;
	private MissionStateTable mission;
	private MissionResult result;
	private String ip;
	private List<FileComment> fileCommentsList;
	public NMSClientTask6(String ip,int port,MissionStateTable mission,Task6 object, MissionResult result,List<FileComment> fileCommentsList)  throws Exception{
		super(ip,port);
		this.ip = ip;
		this.task6 = object;
		this.mission = mission;
		this.result = result;
		this.fileCommentsList = fileCommentsList;
	}

	@Override
	protected String toDo() throws Exception {
		Thread.currentThread().setName("Task 6 id:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
		try {
			//-- 补全任务信息
			task6.setTaskId(mission.getMissionId());
			task6.setTaskType(mission.getMissionType());
			task6.setState(result.getResult());
			//-- 任务信息整理
			StringBuffer warnInfo = new StringBuffer("");
			int trueFileSize = 0;
			List<FileComment> clone = new LinkedList<FileComment>();
			if(fileCommentsList !=null && fileCommentsList.size()>0){
				for(FileComment strs :fileCommentsList){
					FileComment cloneStrs = new FileComment();
					BeanUtils.copyProperties(cloneStrs,strs);
					cloneStrs.setFileName(Constants.MISSION_FILE_DOWNLOAD_DIR+File.separator+cloneStrs.getFileName());
					File file = new File(cloneStrs.getFileName());
					if(!file.exists()){
						trueFileSize++;
						warnInfo.append((file.getAbsolutePath())+" 文件不存在\n");
						logger.warn("File does not exist "+(file.getAbsolutePath()));
					}
					clone.add(cloneStrs);
				}
			}
			if(trueFileSize!=0){
				return "1:"+warnInfo;
			}
			JSONObject object = new JSONObject();
			object.put("typeInfo", mission.getMissionType());
			object.put("taskInfo", task6);
			logger.debug("JSONObject "+object.toString());
			this.sendMessage("byte:upgrade");
			this.receiveMessage();
			this.sendMessage(object.toString());
			this.receiveMessage();
			this.bpSendFileByBathMD5(clone);
			String string =  this.receiveMessage();
			logger.debug("升级部署之文件推送结果 "+string);
			this.sendMessage(SUCCESS);
			return string;
		} catch (Exception e) {
			logger.error("Upgrade deployment failure",e);
			return null;
		}
	}
}
