#include <iostream>
#include "windows.h"
#include "dial.h"
#include "dialchannel.h"

//	This simply demonstrates the usage of the serial channel
//	Data is sent to the Dreamcast and echoed back
//	The ChanEcho program must be running on the dreamcast

namespace
{
	CDial * Dial = 0;
	const int MAX_DATA = 1024;
	const char * Message = "Hello World:- This message was routed to you via the serial channel\n";

	void WriteDataToChannel( DIAL_ID dialID, const char * data, size_t dataLen, size_t& offset )
	{
		//	Continue writing from where we finished last time
		size_t amountToWrite =  dataLen - offset;
		DWORD	amountWritten = 0;
		if( amountToWrite && DIAL_EC_NOERROR == Dial->VSerial.Write( dialID, amountToWrite, amountWritten, data ) )
		{
			offset += amountWritten;
		}
	}

	size_t ReadDataFromChannel( DIAL_ID dialID, char * data, size_t maxSize )
	{
		size_t numRead = 0;
		BOOL ready = FALSE;
		DWORD status = 0;

		//	Check if data is available
		if( DIAL_EC_NOERROR == Dial->VSerial.DataReady( dialID, ready, status ) )
		{
			DWORD amountRead = 0;
			if( DIAL_EC_NOERROR == Dial->VSerial.Read( dialID, maxSize, amountRead, data ) )
			{
				numRead = amountRead;
			}
		}
		return numRead;
	}
}

int main()
{
	//
	//	Initialise and get a pointer to the DIAL library
	//
	Dial = InitializeDial();
	if( Dial )
	{
		//	Find the first device
		DIAL_ID	dialID = DIAL_ID_UNDEF;
		if( DIAL_EC_NOERROR == Dial->FindNextDevice( dialID, DIALDEVICE::DEVTYPE_KATANA_DA ) )
		{
			DIALDEVICE deviceDetails;

			if( DIAL_EC_NOERROR == Dial->GetDeviceDetails( dialID, deviceDetails ) )
			{
				std::cout << "Found device on " << deviceDetails.deviceDesc << std::endl;
			}
			//	Reserve the channel
			if( DIAL_EC_NOERROR == Dial->VSerial.Reserve( dialID ) )
			{
				size_t	offset = 0;
				int		numSent = 0 ;
				while( numSent < 100 )
				{
					WriteDataToChannel( dialID, Message, strlen( Message ), offset );
					if( offset == strlen( Message ) )
					{
						offset = 0;
						++numSent;
					}
					char Buffer[ MAX_DATA + 1 ];
					size_t amountRead = ReadDataFromChannel( dialID, Buffer, MAX_DATA );
					Buffer[ amountRead ] = '\0';
					std::cout << Buffer;
				}
			
				//	Release the channel
				if( DIAL_EC_NOERROR != Dial->VSerial.Release( dialID ) )
				{
					std::cout << "Could not releases the channel." << std::endl;
				}
			}
			else
			{
				std::cout << "Could not reserve the channel" << std::endl;
			}
		}
		else
		{
			std::cout << "Could not find device." << std::endl;
		}
	}
	return 0;
}
