package com.nms.server.thread.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.Calendar;

import org.apache.commons.lang.StringUtils;
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.util.FileUtils;
import com.nms.server.util.UnicodeReader;

/**
 * XML解析线程
 * 
 * @author ZGGG3
 * 
 */
public class ResultFileReaderThread implements Runnable {
	Logger logger = Logger.getLogger(ResultFileReaderThread.class);
	private String dir;
	private String name; // 自定义Thread Name

	public ResultFileReaderThread(String name, String url) {
		this.dir = url;
		this.name = name;
	}

	public void run() {
		// 为当前线程命名 ，用与开发阶段友好输出。
		Thread.currentThread().setName(name+" "+dir);

		try {

			logger.info("文件夹路径 :>" + dir);
			File driFile = new File(dir);

			//获取目录下的.result文件集合
			File[] files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".result")); // 按文件名称 升序排序
			
			// 解析文件数为0时，终止该计划任务
			if(files==null || files.length==0){
				Common.cancelRunnableAtOnce(dir);
				return;
			}
			
			logger.debug("文件夹路径 :>" + driFile.getAbsolutePath() + " 下 "  + files.length + "个文件，解析开始");
			long l = Calendar.getInstance().getTimeInMillis();
			
			if (files != null && files.length > 0) {
				
				for (File file : files) {
					
					if(file.length()>0){
						try {
							BufferedReader reader = new BufferedReader(new UnicodeReader(new FileInputStream(file), Charset.defaultCharset().name()));
							String data = StringUtils.trim(reader.readLine());
							String [] result = StringUtils.isEmpty(data)?null:data.split(Constants.COMMON_DATA_SPLIT);
							
							if(result != null){
								MissionResult2 result2 = Common.resoveMissionResult(result);
								Common.addResultToResultList(result2);
							}
							reader.close();
						} catch (Exception e) {
							logger.error("",e);
						}
					}
					file.delete();
				}
			}
			logger.debug(driFile.getAbsolutePath()+" 解析完成耗时：>"+(Calendar.getInstance().getTimeInMillis()-l));
			//清理
			files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".tp")); // 按文件名称 升序排序
			if(files!=null && files.length>0){
				for(File file : files){
					file.delete();
				}
			}
			logger.debug("清理临时文件完成");
		} catch (Exception e) {
			logger.error("",e);
		}
	}

/*	public static void main(String[] args) {
		long l = Calendar.getInstance().getTimeInMillis();
		Future<?> future = Common.service.submit(new FileReaderThread("文件解析线程", "D:\\cvs\\10.0.6.10"));
		try {
			future.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Calendar.getInstance().getTimeInMillis()-l);
	}*/
}
