package com.nms.server.thread.deleteFiles;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;

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

import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;

/**
 * 定时删除指定文件
 * 2013-3-14 hyx
 */
public class DeleteFilesThread implements Runnable{
	private Logger logger = Logger.getLogger(DeleteFilesThread.class);
	
	@Override
	public void run() {
		Thread.currentThread().setName("Regularly Delete Files (log, error->detect, download) Thread");
		try {
			
			//删除日志文件：只处理绝对路径
			ResourceBundle log4jRb = ResourceBundle.getBundle("log4j");
			String logFileStr = null;
			try {
				logFileStr = log4jRb.getString("log4j.appender.logfile.File");
			} catch (Exception e) {
				logger.info("未找到 旧格式日志文件路径 跳过旧格式日志删除");
			}
			
			if(StringUtils.isNotBlank(logFileStr)){
				File logFile = new File(logFileStr);
				if(logFile!=null&&logFile.isAbsolute()) {
					String logPath = logFile.getParent();
					File tmpFiles = new File(logPath);
					if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
						logger.info("删除日志文件开始");		
						int delLogFilesNum = deleteFilesFrom(logPath,"日志");
						logger.info("删除日志文件结束，共删除"+delLogFilesNum+"个文件");		
					}
				}
			}
			
			//删除download里的文件
			String downloadPath = Constants.MISSION_FILE_DOWNLOAD_DIR;
			if(StringUtils.isNotBlank(downloadPath)) {
				logger.info("删除download文件开始");		
				int delDownloadFilesNum = deleteFilesFrom(downloadPath,"download");
				logger.info("删除download文件结束，共删除"+delDownloadFilesNum+"个文件");
			}
			
			//删除error里的detect里的文件，按文件名进行删除
			String detectPath = Constants.ERROR_DETEC_FILE_DIR;
			if(StringUtils.isNotBlank(detectPath)) {
				logger.info("删除detect文件开始");		
				int delDetectFilesNum = deleteFilesFromByFileName(detectPath,"detect");
				logger.info("删除detect文件结束，共删除"+delDetectFilesNum+"个文件夹");
			}
			
		} catch (Exception e) {
			logger.error("Regularly delete files (log, error->detect, download) exceptions",e);
		}
	}
	
	//pathNam：要删除的文件所在的路径
	private int deleteFilesFrom(String pathName,String tip) throws Exception{
		File tmpFiles = new File(pathName);
		int deleteFileNum = 0;
		if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
			logger.info(tip+"文件所在路径："+pathName);		
			
			if(tmpFiles.exists()) {
//				File[] filesTmp = FileUtils.listAllFilesEndWith(logFiles, "txt");
				File[] filesTmp = tmpFiles.listFiles();
				if(filesTmp!=null&&filesTmp.length>0) {
					Date now = new Date();
					Calendar nowCal = Calendar.getInstance();    
					nowCal.setTime(now);
					
					nowCal.set(Calendar.HOUR, nowCal.get(Calendar.HOUR)-Constants.KEEP_FILE_DAYS*24);
//					nowCal.set(Calendar.MINUTE, nowCal.get(Calendar.MINUTE)-1);//测试时使用
					for(File f:filesTmp) {
						Calendar lastModifyTime = FileUtils.getModifiedTime(f);
						if(nowCal.compareTo(lastModifyTime)>0) {
//							boolean isDel = f.delete();//删除文件夹时，文件夹必须是空的才可以
							FileUtils.deleteAllFiles(f,true);
//							if(isDel) {
								deleteFileNum++;
//							}
						}						
					}
				}
			}			
		}
		return deleteFileNum;
	}
	
	private int deleteFilesFromByFileName(String pathName,String tip) throws Exception{
		File tmpFiles = new File(pathName);
		int deleteFileNum = 0;
		if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
			logger.info(tip+"文件所在路径："+pathName);			
			
			if(tmpFiles.exists()) {
//				File[] filesTmp = FileUtils.listAllFilesEndWith(logFiles, "txt");
				File[] filesTmp = tmpFiles.listFiles();
				if(filesTmp!=null&&filesTmp.length>0) {
					Date now = new Date();
					Calendar nowCal = Calendar.getInstance();    
					nowCal.setTime(now);
					nowCal.set(Calendar.HOUR, nowCal.get(Calendar.HOUR)-Constants.KEEP_FILE_DAYS*24);
//					nowCal.set(Calendar.MINUTE, nowCal.get(Calendar.MINUTE)-5);//测试时使用
					for(File f:filesTmp) {
//						Calendar lastModifyTime = FileUtils.getModifiedTime(f);
						String fileName = f.getName();
						SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
						try
						{
							Date date = format.parse(fileName);
							Calendar lastModifyTime = Calendar.getInstance();
							lastModifyTime.setTime(date);
							if(nowCal.compareTo(lastModifyTime)>0) {
								FileUtils.deleteAllFiles(f,true);//删除文件夹时，文件夹必须是空的才可以
								deleteFileNum++;
							}						
						} catch (ParseException e)
						{
							logger.info("删除 detect文件时，解析"+pathName+"路径下的文件夹名称，转换为日期形式   异常");
						}
					}
				}
			}			
		}
		return deleteFileNum;
	}
	
	public static void main(String [] args){
		new Thread(new DeleteFilesThread()).start();
		
	}
	
}
