package com.hand.mas.ant.task;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

import com.hand.mas.ant.service.SqlPlusService;
import com.hand.mas.ant.util.LogUtil;

public class SqlPlusTask extends Task {
	private File file = null;
	private File dir = null;
	private Long timeout = 30000L;

	private Vector filesets = new Vector();

	private String dbuser = null;
	private String dbpass = null;
	private String tnsname = null;
	private String logOn = null;
	private String dupexec = null;
	private String dupexectime = null;
	// 默认不进行多次执行。当多次执行的次数没有指定的时候，次数默认为3
	private boolean isDupExec = false;
	private int dupTime = 3;

	private String logFilePath = null;
	private File logFile = null;

	@Override
	public void init() {
		Project project = this.getProject();
		if (project == null) {
			throw new BuildException("No Project Define!");
		}
		this.logFilePath = project.getProperty("LogFilePath");
		this.logFile = new File(project.getBaseDir().getAbsolutePath() + "/"
				+ logFilePath);
	}

	@Override
	public void execute() {
		if (this.dbuser == null || this.dbpass == null || this.tnsname == null) {
			throw new BuildException(
					"the dbHost or dbPort or dbuser or dbpass is not defined!");
		}
		this.logOn = dbuser + "/" + dbpass + "@" + tnsname;

		if (file == null && dir == null && filesets == null) {
			throw new BuildException("No Files or Dir exists");
		}

		if (dupexec != null && dupexec.equals("true")) {
			isDupExec = true;
			if (dupexectime != null) {
				try {
					dupTime = Integer.parseInt(dupexectime);
				} catch (NumberFormatException e) {
					this.log("多次执行次数输入错误，输入并非数字，请检查！");
					dupTime = 3;
				}
			}
		}

		if (file != null) {
			if (file.isDirectory()) {
				throw new BuildException("The file is a directory");
			}
			if (file.length() == 0) {
				throw new BuildException(
						"The file length is 0,please check the file!");
			}
			String command = "sqlplus " + logOn + " @" + file.getAbsolutePath();
			SqlPlusService sps = new SqlPlusService(this);
			sps.setCommands(command);
			try {
				sps.run();
			} catch (Exception e) {
			}
		} else if (dir != null) {
			HashSet<String> errFileSet = new HashSet<String>();
			if (!file.isDirectory()) {
				throw new BuildException("The file is not directory");
			}
			File fs[] = dir.listFiles();
			SqlPlusService sps = new SqlPlusService(this);
			for (File f : fs) {
				String command = "sqlplus " + logOn + " @"
						+ f.getAbsolutePath();
				sps.setCommands(command);
				try {
					sps.run();
				} catch (Exception e) {
					errFileSet.add(dir.getAbsolutePath() + "/"
							+ f.getAbsolutePath());
				}
			}
			if (isDupExec) {
				for (int dt = 0; dt < dupTime; dt++) {
					Iterator<String> iterator = errFileSet.iterator();
					while (iterator.hasNext()) {
						String fileName = (String) iterator.next();
						String command = "sqlplus " + logOn + " @"
								+ fileName;
						sps.setCommands(command);
						try {
							sps.run();
							iterator.remove();
						} catch (Exception e) {
							// 当前执行的就是错误文件，不需要再将其放入错误文件列表中
						}

					}
//					for (String fileName : errFileSet) {
//						String command = "sqlplus " + logOn + " @"
//								+ fileName;
//						sps.setCommands(command);
//						try {
//							sps.run();
//							errFileSet.remove(fileName);
//						} catch (Exception e) {
//							// 当前执行的就是错误文件，不需要再将其放入错误文件列表中
//						}
//					}
				}
				try {
					Iterator<String> iterator = errFileSet.iterator();
					while (iterator.hasNext()) {
						String fileName = (String) iterator.next();
						LogUtil.logError(fileName + "无法执行");
						LogUtil
								.logError("============================================");
					}
				} catch (Exception e) {
					this.log(e.getMessage());
				}
			}

		} else if (filesets != null) {
			HashSet<String> errFileSet = new HashSet<String>();
			for (Object o : filesets) {
				FileSet fileset = (FileSet) o;
				File dir = fileset.getDir();
				DirectoryScanner sc = fileset.getDirectoryScanner();
				String files[] = sc.getIncludedFiles();
				if (!dir.isDirectory()) {
					throw new BuildException("The file is not directory");
				}
				File fs[] = dir.listFiles();
				SqlPlusService sps = new SqlPlusService(this);
				for (String f : files) {
					try {
						String command = "sqlplus " + logOn + " @"
								+ dir.getAbsolutePath() + "/" + f;
						sps.setCommands(command);
						sps.run();
					} catch (Exception e) {
						errFileSet.add(dir.getAbsolutePath() + "/" + f);
					}
				}

				if (isDupExec) {
					for (int dt = 0; dt < dupTime; dt++) {
						Iterator<String> iterator = errFileSet.iterator();
						while (iterator.hasNext()) {
							String fileName = (String) iterator.next();
							String command = "sqlplus " + logOn + " @"
									+ fileName;
							sps.setCommands(command);
							try {
								sps.run();
								iterator.remove();
							} catch (Exception e) {
								// 当前执行的就是错误文件，不需要再将其放入错误文件列表中
							}

						}
//						for (String fileName : errFileSet) {
//							String command = "sqlplus " + logOn + " @"
//									+ fileName;
//							sps.setCommands(command);
//							try {
//								sps.run();
//								errFileSet.remove(fileName);
//							} catch (Exception e) {
//								// 当前执行的就是错误文件，不需要再将其放入错误文件列表中
//							}
//						}
					}
					try {
						Iterator<String> iterator = errFileSet.iterator();
						while (iterator.hasNext()) {
							String fileName = (String) iterator.next();
							LogUtil.logError(fileName + "无法执行");
							LogUtil
									.logError("============================================");
						}
					} catch (Exception e) {
						this.log(e.getMessage());
					}
				}
			}
		}
	}

	public void addFileSet(FileSet fileset) {
		this.filesets.add(fileset);
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void setDir(File dir) {
		this.dir = dir;
	}

	public void setTimeout(Long timeout) {
		this.timeout = timeout;
	}

	public void setDbuser(String dbuser) {
		this.dbuser = dbuser;
	}

	public void setDbpass(String dbpass) {
		this.dbpass = dbpass;
	}

	public void setTnsname(String tnsname) {
		this.tnsname = tnsname;
	}

	public void setDupexec(String dupexec) {
		this.dupexec = dupexec;
	}

	public void setDupexectime(String dupexectime) {
		this.dupexectime = dupexectime;
	}
}
