/*
 * rfc2544.c
 *
 *  Created on: 29 Sep 2015
 *      Author: Niall.Donovan
 */

#include <api_oam_sdk/rmep_db/src/rmep_types.h>
#include <api_oam_sdk/service_activation/inc/rfc2544.h>
#include <api_oam_sdk/service_activation/src/service_activation_types.h>
#include "string.h"

extern rfc2544Cfg_t		saRfc2544Cfg;
extern rfc2544Results_t	saRfc2544Results;
testStatus_t 			rfc2544Status = test_disabled;

/**
 * @brief Configure the device to run the RFC2544 tests
 *
 */
int rfc2544Configure(rfc2544Cfg_t *rfc2544Cfg)
{
	if (rfc2544Cfg != NULL)
	{
		return(rfc2544UpdateConfig(rfc2544Cfg));
	}
	return(1);
}

/**
 * @brief Start the RFC2544 tests using the current configuration
 */
int rfc2544Start(void)
{
	int 			retVal;
	bool 			macValid;
	macAddress_t	macAddress;

#if 0
	if (0)
	{
		return(1);			// Operation rejected because the port selected is down.
	}
#endif

	if (!(saRfc2544Cfg.enThroughput || saRfc2544Cfg.enFrameLoss || saRfc2544Cfg.enDelay || saRfc2544Cfg.enBackToBack) )
	{
		return(2);			// Operation rejected because no tests are selected to run.
	}

	rMepGetMAC(saRfc2544Cfg.targetMep.mdIndex, saRfc2544Cfg.targetMep.maIndex, saRfc2544Cfg.targetMep.lMepId, saRfc2544Cfg.targetMep.rMepId, &macValid, macAddress);
	if (!macValid)
	{
		return(-1);				// Target MEP MAC is unknown.
	}

	rfc2544Status = test_running;

	retVal = rfc2544RunTests();
	if (retVal == 1)
	{
		return(3);			// Operation rejected because another Service activation test is already running
	}
	return(4);				// Operation successful
}

/**
 * @brief Stop the current RFC2544 test
 */
int rfc2544Stop(void)
{
	int	retVal;

	retVal = saStopTest();
	rfc2544Status = test_stopped;

	return(retVal);
}

/**
 * @brief Read the status and results for the RFC2544 tests.
 */
int rfc2544Read(testStatus_t *testStatus, rfc2544Cfg_t *rfc2544Cfg, rfc2544Results_t *rfc2544Results)
{
	if (rfc2544Cfg != NULL)
	{
		LOCK_SA_READ(0);
		memcpy(rfc2544Cfg, &saRfc2544Cfg, sizeof(rfc2544Cfg_t));
		UNLOCK_SA_READ();
	}

	if (rfc2544Results != NULL)
	{
		LOCK_SA_READ(0);
		memcpy(rfc2544Results, &saRfc2544Results, sizeof(rfc2544Results_t));
		UNLOCK_SA_READ();
	}

	if (testStatus != NULL)
	{
		*testStatus = rfc2544Status;
	}
	return(1);
}
