/*
 * Run scans and arbitrate the results
 *
 * Copyright (C) 2003--2007  Enrico Zini <enrico@debian.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "runner/runner.h"
#include <sys/time.h>
#include <time.h>

using namespace std;
using namespace scanner;
using namespace wibble::sys;

namespace runner {

Runner::Runner()
{
	ScanBag::get().setListener(this);
}

void Runner::candidatesChanged()
{
	MutexLock lock(waitMutex);
	vector<string> candidates = ScanBag::get().getRemaining();
	if (candidates.size() == 1)
		waitCond.broadcast();
}

/// Wait for an answer from the tests for no more than `timeout' milliseconds
string Runner::getResult(int timeout)
{
	struct timeval before;
	gettimeofday(&before, 0);
	struct timespec abstime;
	abstime.tv_sec = before.tv_sec;
	abstime.tv_nsec = before.tv_usec * 1000;

	abstime.tv_sec += timeout / 1000;
	abstime.tv_nsec += (timeout % 1000) * 1000000;
	if (abstime.tv_nsec > 1000000000)
	{
		abstime.tv_sec++;
		abstime.tv_nsec -= 1000000000;
	}

	MutexLock lock(waitMutex);

	// Try once before waiting, in case we have something already
	string final = ScanBag::get().getFinal();
	if (final.empty())
	{
		// Nothing yet, let's wait for something
		waitCond.wait(lock, abstime);

		// If we still don't have a winner, then we timed out and we use the
		// default
		final = ScanBag::get().getFinal();
		if (final.empty())
			final = ScanBag::get().getDefault();
	}

	return final;
}

}

// vim:set ts=4 sw=4:
