#include "ProcTools.h"


Vector<String> ProcTools::ParseArgLine(String const &argLine)
{
	Vector<String> args;
	
	// skips leading spaces
	char c;
	int pos = 0;
	while ((c = argLine[pos]) != 0 && isspace(c))
		pos++;

	// loop reading args and putting to array
	while (c)
	{
		String &s = args.Add();
		while (c && !isspace(c))
		{
			// reads enquoted strings
			if (c == '"')
			{
				c = argLine[++pos];
				while (c && c != '"')
				{
					s << c;
					c = argLine[++pos];
				}
				if (c)
					c = argLine[++pos];
			}
			// read single quoted string
			else if(c == '\'')
			{
				c = argLine[++pos];
				while (c && c != '\'')
				{
					s << c;
					c = argLine[++pos];
				}
				if (c)
					c = argLine[++pos];
			}
			else
			{
				s << c;
				c = argLine[++pos];
			}

		}
		// skips trailing spaces
		while (c && isspace(c))
			c = argLine[++pos];
	}
	return args;
}

ProcTools::ProcTools()
{
	Clear();
}

ProcTools &ProcTools::Clear(void)
{
	_out.Clear();
	_err.Clear();
	if(_proc.IsRunning())
		_proc.Kill();

	return *this;
}

bool ProcTools::Exec(String const &cmd, String const &argLine)
{
/*
	Vector<String> args = ParseArgLine(argLine);
	_proc.Start2(cmd, args);
*/
// DUMP(cmd + " " + argLine);
_proc.Start2(cmd + " " + argLine);
	while(_proc.IsRunning())
	{
		String o, e;
		_proc.Read2(o, e);
		_out << o;
		_err << e;
		if(WhenOutput)
			if(WhenOutput(o))
				_proc.Kill();
		if(WhenOutErr)
			if(WhenOutErr(o, e))
				_proc.Kill();
		Sleep(10);
	}
	String o, e;
	_proc.Read2(o, e);
	_out << o;
	_err << e;
	return !_proc.GetExitCode();
}

bool ProcTools::Exec(String const &cmdLine)
{
/*
	Vector<String> args = ParseArgLine(cmdLine);
	String cmd = args[0];
	args.Remove(0);
	_proc.Start2(cmd, args);
*/
// DUMP(cmdLine);
_proc.Start2(cmdLine);
	while(_proc.IsRunning())
	{
		String o, e;
		_proc.Read2(o, e);
		_out << o;
		_err << e;
		if(WhenOutput)
			if(WhenOutput(o))
				_proc.Kill();
		if(WhenOutErr)
			if(WhenOutErr(o, e))
				_proc.Kill();
		Sleep(10);
	}
	String o, e;
	_proc.Read2(o, e);
	_out << o;
	_err << e;
	return !_proc.GetExitCode();
}
		