package com.hand.mas.ant.service;

import java.util.Scanner;

import org.apache.tools.ant.Task;

import com.hand.mas.ant.exception.LogErrorException;
import com.hand.mas.ant.exception.LogWarnException;
import com.hand.mas.ant.util.LogUtil;
import com.hand.mas.ant.util.SysExcUtil;
import com.hand.mas.ant.util.TimeoutMonitor;


public class SqlPlusService implements AbstractService{
	
	private Long timeOut = 60000L;
	private Task task;
	private Runtime rt = Runtime.getRuntime();
	private String command;
	private boolean isLinux;
	
	Boolean errorFlag = false;
	Boolean appExitFlag = false;
	
	public SqlPlusService(Task owner,Long timeOut){
		this.timeOut = timeOut;
		this.task = owner;
		this.isLinux = true;
	}
	
	public SqlPlusService(Task owner){
		this.task = owner;
		this.isLinux = true;
	}
	
	public void run() throws Exception{
		try{
			Process proc = null;
			if(isLinux){
				proc = rt.exec(command);	
			}else{
				proc = rt.exec(SysExcUtil.getCmd(command));
			}
			processPrint(proc);
			task.log(command + "\n---------------------------------------------ok");
		}catch(LogErrorException e){
			task.log(command + "\n---------------------------------------------failure");
			LogUtil.logError(command + "无法执行");
			LogUtil.logError("============================================");
			throw e;
		}catch(LogWarnException e){
			task.log(command + "\n---------------------------------------------warn");
			LogUtil.logWarn(command + "执行带有警告或错误");
			LogUtil.logWarn("============================================");
			throw e;
		}
	}

	private void processPrint(Process proc) throws Exception{
		boolean hasWarn = false;
		TimeoutMonitor tm = new TimeoutMonitor(timeOut, proc);
		Thread deamon = new Thread(tm);
		deamon.start();
		
		Scanner sc = new Scanner(proc.getInputStream());
		while(sc.hasNextLine()){
			String outStr = sc.nextLine();
			if(!hasWarn){
				hasWarn = hasWarn(outStr);
			}
			System.out.print(" ");
			if(hasWarn){
				LogUtil.logWarn(outStr);
			}
		}
		deamon.interrupt();
		if(!tm.successFlag){
			throw new LogErrorException("文件执行错误");
		}
		
		if(hasWarn){
			throw new LogWarnException("文件执行存在警告");
		}
	}
	
	public boolean hasWarn(String testStr){
//		Pattern p = Pattern.compile("ORA");
//		Matcher m = p.matcher(testStr);
		if(testStr.contains("ORA")||testStr.contains("错误")||testStr.contains("ERROR")||testStr.contains("\\*")){
			return true;
		}else{
			return false;
		}
	}
	
	public void setTimeOut(Long timeOut) {
		this.timeOut = timeOut;
	}

	public void setCommands(String command){
		this.command = command;
	}
	
	public void setErrorFlag(Boolean errorFlag) {
		this.errorFlag = errorFlag;
	}

	public void setAppExitFlag(Boolean appExitFlag) {
		this.appExitFlag = appExitFlag;
	}
}
