/*
 *  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
 */

#pragma warning(disable:4786)

#include <iostream>
#include "Be.h"

using namespace std;


// threadStart
int32 threadStart (void* arg)
{
	thread_id thread2 = find_thread (0);
	if (thread2 != 0)
		cout << "thread2 found from null" << endl;

	snooze (1000005);

	return 666;
}


// test_result
class Tester
{
public:
	Tester () : tests (0), successes (0) {;}

	void test_result (const char* test, bool result)
	{
		tests++;
		if (result) {
			cout << "success: ";
			successes++;
		} else
			cout << "ERROR: ";

		cout << test << std::endl;
	}

	~Tester ()
	{
		cout << std::endl << tests << " tests, " << tests - successes << " failures" << std::endl;
	}

protected:
	int tests;
	int successes;
};


// main
int main (int argc, char** argv)
{
	Tester t;

	// Threads

	thread_id thread2 = spawn_thread (threadStart, "thread2", B_LOW_PRIORITY, 0);
	t.test_result ("create thread2", thread2 != 0);

	thread_id mainThread = find_thread (0);
	t.test_result ("find main thread from null", mainThread != 0);

	thread_id thread2_duplicate = find_thread ("thread2");
	t.test_result ("find thread2 from name", thread2_duplicate == thread2);

	status_t result = resume_thread (thread2);
	t.test_result ("resume thread2", result == B_NO_ERROR);

	thread_info info;
	result = get_thread_info (thread2, &info);
	t.test_result ("get thread2 info", result != B_BAD_VALUE);

	status_t exitValue;
	wait_for_thread (thread2, &exitValue);
	t.test_result ("wait for thread2", exitValue == 666);

	// Semaphores

	sem_id sem1 = create_sem (1, "sem1");
	t.test_result ("create sem1", sem1 != 0);

	status_t status = acquire_sem (sem1);
	t.test_result ("acquire sem1", status == B_NO_ERROR);

	status = acquire_sem_etc (sem1, 1, B_TIMEOUT, 1000000);
	t.test_result ("acquire sem1 again", status == B_TIMED_OUT);

	int32 count;
	status = get_sem_count (sem1, &count);
	t.test_result ("get sem1 count", count == 0);

	status = release_sem (sem1);
	t.test_result ("release sem1", status == B_NO_ERROR);

	status = get_sem_count (sem1, &count);
	t.test_result ("get sem1 count again", count == 1);

	status = delete_sem (sem1);
	t.test_result ("delete sem1", status == B_NO_ERROR);

	return 0;
}
