// Copyright (c) 2020 Metrolab Technology S.A., Geneva, Switzerland (www.metrolab.com)
// See the included file LICENSE.txt for the licensing conditions.

//////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Test THM1176 API: Utility functions.

#include "THM1176TestUtilities.h"
#include "Helpers.h"
#include "Exception.h"

using namespace MTL::Instrument;
using namespace MTL::Instrument::THM1176Types;

bool FetchTHM1176Resource (THM1176_TEST_RESOURCE_MANAGER_CLASS & rResourceManager, tResourceName & rTHM1176)
{
	try
	{
		// Open a connection to the the resource manager
		if (!rResourceManager.Initialize())
			throw MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS>("Could not initialize resource manager", MTL__LOCATION__);
		
		// Find all THM1176 instruments.
		CResourceList l_THM1176List;
		if (!rResourceManager.FindResources(l_THM1176List, THM1176_TEST_RESOURCE_FILTER) || l_THM1176List.empty())
			throw MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS>("Could not find THM1176", MTL__LOCATION__);
		
		// Run the tests on the first one in the list.
		rTHM1176 = l_THM1176List.front();
	}
	catch (MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS> & rE)
	{
		std::cout << "l_CManagerException: " << rE.what() << std::endl;
		rTHM1176 = "";
		return false;
	}
	
	return true;
}

bool ConnectToTHM1176 (THM1176_TEST_RESOURCE_MANAGER_CLASS	* & rpResourceManager, CTHM1176Instrument<THM1176_TEST_INSTRUMENT_CLASS, THM1176_TEST_RESOURCE_MANAGER_CLASS> * & rpTHM1176)
{
	try
	{
		// Create the resource manager.
		rpResourceManager = new THM1176_TEST_RESOURCE_MANAGER_CLASS;
		
		// Fetch the THM1176 resource name.
		tResourceName			l_THM1176;
		if (!FetchTHM1176Resource(*rpResourceManager, l_THM1176))
			throw MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS>("Could not find THM1176", MTL__LOCATION__);
		
		// Create the THM1176 object.
		rpTHM1176 = new CTHM1176Instrument<THM1176_TEST_INSTRUMENT_CLASS, THM1176_TEST_RESOURCE_MANAGER_CLASS>(*rpResourceManager, l_THM1176);
		if (NULL == rpTHM1176)
			throw MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS>("Unable to create THM1176 object", MTL__LOCATION__);
		
		// Connect to the THM1176.
		static const U32		l_THM1176_TIMEOUT = 5000;	// ms
		if (!rpTHM1176->Connect(l_THM1176_TIMEOUT))
			throw MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS>("Unable to connect to THM1176", MTL__LOCATION__);
	}
	catch (MTL::CException<THM1176_TEST_RESOURCE_MANAGER_CLASS> & rE)
	{
		std::cout << "l_CManagerException: " << rE.what() << std::endl;
		rpTHM1176 = NULL;
		return false;
	}
	return true;
}


