// Thomas Braunl, UWA 2017
// Radio station demo

#include <stdio.h>
#include <stdlib.h>
#include "radio.h"
#include <winsock2.h>
#include <ws2tcpip.h>
//#include <windows.h>
//#include "stdafx.h"

#define MAX 1024

int main ()
{ 
	int l, i, j;
	int id[256];
	int myid,partnerid; 
	char bufS[MAX];
	char *bufR = (char*)malloc(MAX * sizeof(char));
  
	SOCKET sockfdListening = INVALID_SOCKET;
	//SOCKET sockfdReceiving = INVALID_SOCKET;

	printf("Initializing Radio\n");
	sockfdListening=RADIOInit(sockfdListening);

	myid = RADIOGetID();
	//printf("My id is %d\n", myid);

	printf("Do you want to scan whole network for active devices? (y/n)\n");
	char scan;
	scanf(" %c", &scan);
	if (scan == 'Y' | scan=='y')
		PingNetwork();
  // Use Ping Netwrok only if the Host is unabale to find the robots in network.
  // Pinging all the IP adressess takes time but it also updates the ARP cache with all available devices/
  // Function RadioStatus uses the ARP cache to identify the robots among other devices.
	printf("Scanning for Robots...\n");
	l = RADIOStatus(id); 
	RADIOCheck();
	if (l > 0)
	{
		printf("IP of active Eyebots: ");
		for (i = 0; i < l; i++)
		{
			printf("%d  ", id[i]);
			partnerid = id[i];
		}
		printf("\n");
		printf("Initiating communication with EyeBots\n");
		for (i = 0; i < l; i++)
		{
			partnerid = id[i];
			
			//printf("Exchanging addresses with Prefix\n");
			sprintf(bufS, "%d Host ID %d\n", partnerid, myid);
			printf("Sending Host ID to %d\n",partnerid);
			RADIOSend(partnerid, bufS, sockfdListening);
			if (RADIOReceive(partnerid, bufR) == 1)
				printf("Received response from %s \n", bufR);
			else
			{
				printf("%d did not respond \n", partnerid);
				continue;
			}
			printf("Waiting for Client to initiate Ping Pong\n");
			for (j = 0; j<5; j++)
			{
				RADIOReceive(partnerid, bufR);
				printf("Received %s", bufR);
				int b = atoi(bufR);
				b++;
				sprintf(bufS, "%d", b);
				RADIOSend(partnerid, bufS, sockfdListening);
				printf("Sent %s\n\n",bufS);
			}
		  
			Sleep(2000);
		}

		printf("Done communicating with all robots\n");
	}
	else
	{
		printf("No other robots found.\n");
		partnerid = 0;
	}
	RADIOCheck();
	printf("Program will terminate in 5 sec\n");
	RADIORelease(sockfdListening);
	Sleep(5000);
}

