package org.bench4q.agent.plugin.basic.comandline;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.bench4q.agent.plugin.Constructor;
import org.bench4q.agent.plugin.Parameter;
import org.bench4q.agent.plugin.Plugin;
import org.bench4q.agent.plugin.behavior.Behavior;
import org.bench4q.agent.plugin.behavior.BehaviorType;
import org.bench4q.agent.utils.Type.SupportTypes;

@Plugin("CommandLine")
public class CommandLinePlugin {
	private String standardOutput;
	private String standardError;

	public String getStandardOutput() {
		return standardOutput;
	}

	private void setStandardOutput(String standardOutput) {
		this.standardOutput = standardOutput;
	}

	public String getStandardError() {
		return standardError;
	}

	private void setStandardError(String standardError) {
		this.standardError = standardError;
	}

	@Constructor
	public CommandLinePlugin() {

	}

	@Behavior(value = "Command", type = BehaviorType.USER_BEHAVIOR)
	public CommandLineReturn command(
			@Parameter(value = "command", type = SupportTypes.Field) String command) {
		try {
			final Process process = Runtime.getRuntime().exec(command);
			new Thread() {
				public void run() {
					try {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(process.getInputStream()));
						String streamline = "";
						try {
							setStandardOutput("");
							while ((streamline = reader.readLine()) != null) {
								setStandardOutput(getStandardOutput()
										+ streamline
										+ System.getProperty("line.separator"));
							}
						} finally {
							reader.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
			new Thread() {
				public void run() {
					try {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(process.getErrorStream()));
						String streamline = "";
						try {
							setStandardError("");
							while ((streamline = reader.readLine()) != null) {
								setStandardError(getStandardError()
										+ streamline
										+ System.getProperty("line.separator"));
							}
						} finally {
							reader.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
			process.waitFor();
			return new CommandLineReturn(true);
		} catch (Exception e) {
			e.printStackTrace();
			return new CommandLineReturn(false);
		}
	}
}
