/*
 * ReceiveHealth.c
 * 
 * Gocator 2000 Sample
 * Copyright (C) 2011 by LMI Technologies Inc.
 * 
 * Licensed under The MIT License.
 * Redistributions of files must retain the above copyright notice.
 *
 * Purpose: Connect to Gocator system and receive data
 *
 */
#include <Go2.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define NUM_MESSAGES	10
#define RECEIVE_TIMEOUT	20000 

void main(int argc, char **argv)
{
	int status;
	Go2System system = GO2_NULL;
	Go2Health health = GO2_NULL;
	Go2IPAddress address;
	unsigned int i;
	unsigned int j;


	// initialize Go2 API
	if ((status = Go2Api_Initialize()) != GO2_OK)
	{
		printf("Error: Go2Api_Initialize:%d\n", status);
		return;
	}

	// construct Go2 system object
	if ((status = Go2System_Construct(&system)) != GO2_OK)
	{
		printf("Error: Go2System_Construct:%d\n", status);
		return;
	}

	// convert ip address string to Go2IPAddress object
	if ((status = Go2IPAddress_Parse("192.168.1.10", &address)) != GO2_OK)
	{
		printf("Error: Go2IPAddress_Parse:%d\n", status);
		return;
	}

	// connect to Gocator system at default address
	if ((status = Go2System_Connect(system,address)) != GO2_OK)
	{
		printf("Error: Go2System_Connect:%d\n", status);
		return;
	}

	// establish a Gocator health channel connection	
	if ((status = Go2System_ConnectHealth(system, GO2_NULL, GO2_NULL)) != GO2_OK)
	{
		printf("Error: Go2System_ConnectHealth:%d\n", status);
		return;
	}

	//loop until 10 results are received
	i = 0;
	while (i < NUM_MESSAGES)
	{
		if ((status = Go2System_ReceiveHealth(system, RECEIVE_TIMEOUT, &health)) == GO2_OK)
		{
			printf("Health message received:\n"); 
			printf("  Number of indicators: %d\n", Go2Health_Count(health)); 
			
			for (j = 0; j < Go2Health_Count(health); ++j)
			{
				printf("  Indicator[%u]: Id:%lld Instance:%lld Value:%lld\n", j, Go2Health_IdAt(health, j), Go2Health_InstanceAt(health, j), Go2Health_ValueAt(health, j)); 
			}
			if ((status = Go2Health_Destroy(health)) != GO2_OK)
			{
				printf("Error: Go2Health_Destroy:%d\n", status);
				return;
			}
			i++;
		}
		else if (status == GO2_ERROR_TIMEOUT)
		{
			printf("Timeout in Go2System_ReceiveHealth...\n");
		}
		else
		{
			printf("Error: Go2System_ReceiveHealth:%d\n", status);
			return;
		}
	}

	// destroy system handle
	if ((status = Go2System_Destroy(system)) != GO2_OK)
	{
		printf("Error: Go2System_Destroy:%d\n", status);
		return;
	}

	// terminate Go2 API
	if ((status = Go2Api_Terminate()) != GO2_OK)
	{
		printf("Error: Go2Api_Terminate:%d\n", status);
		return;
	}

	printf("Press any key to continue...\n", status);
	getchar();

	return;
}