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.MissionStateTable;
import com.nms.server.bean.Task1;
import com.nms.server.common.Constants;
import com.nms.server.util.socket.SSLSocketCallable;
import com.socket.utils.FileComment;

public class NMSClientTask1 extends SSLSocketCallable{
	private final Logger logger = Logger.getLogger(NMSClientTask1.class);
	private Task1 task1 ;
	private MissionStateTable mission;
	private List<FileComment> fileCommentsList;
	public NMSClientTask1(String ip,int port,MissionStateTable mission,Task1 object,List<FileComment> fileCommentsList) throws Exception{
		super(ip,port);
		this.task1 = object;
		this.mission = mission;
		this.fileCommentsList = fileCommentsList;
	}
	@Override
	protected String toDo() throws Exception {

		try {
			Thread.currentThread().setName("Task:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
			task1.setTaskId(mission.getMissionId());
			task1.setTaskType(mission.getMissionType());
			StringBuffer warnInfo = new StringBuffer("");
			int trueFileSize = 0;
			
			List<FileComment> clone = new LinkedList<FileComment>();
			
			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", task1);
			logger.debug("JSONObject "+object.toString());
			this.sendMessage("byte:filePush");
			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("File push failed",e);
			return null;
		}
	}
}
