/*
This program is distributed under the terms of the 'MIT license'. The text
of this licence follows...

Copyright (c) 2006 J.D.Medhurst (a.k.a. Tixy)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
@file

@brief Implementation of #SerialPort for Windows.
*/

#include "../../common/common.h"
#include "../ymodem_tx.h"


#include "windows.h"


// comment in next line to get a log of all port trafic...
// #define DEBUG_LOG

#ifdef DEBUG_LOG
#include "stdio.h"
#endif


/**
@brief Serial port object for Windows.
@ingroup serialport
*/
class WindowsSerialPort : public SerialPort
	{
public:
	WindowsSerialPort();
	int Open(unsigned port);
	int Initialise(unsigned baud);
	int Out(const uint8_t* data, size_t size, unsigned timeout);
	int In(uint8_t* data, size_t maxSize, unsigned timeout);
	void Close();
private:
	~WindowsSerialPort();
	int Error(int defaultError=ErrorUnspecified);
private:
	HANDLE hSerial; /**< File handle for serial port. */
#ifdef DEBUG_LOG
	void DebugDump(const char* prefix, const uint8_t* data, size_t size);
	FILE* DebugLog;
#endif
	};


/**
Process a Windows error.

@param defaultError	The default error value to return.

@return An error value from #Errors
*/
int WindowsSerialPort::Error(int defaultError)
	{
#ifdef DEBUG_LOG
	char errorMessage[1024];
	DWORD error = GetLastError();
	FormatMessage
		(
		FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		error,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		errorMessage,
		sizeof(errorMessage),
		NULL
		);
	OutputDebugString(errorMessage);
	if(DebugLog)
		fprintf(DebugLog,"ERROR: Windows error %d : %s",error,errorMessage);
	BREAKPOINT;
//	MessageBox( NULL, errorMessage, "Error", MB_OK | MB_ICONINFORMATION );
#endif
	// if we wanted to we could convert a Windows error from GetLastError()
	// into one of our error values, but just return defaultError...
	return defaultError;
	}


int WindowsSerialPort::Open(unsigned port)
	{
	// make name for port...
	char name[] = "\\\\.\\com???.???";
	char* nameNumber = name+sizeof(name)-8;
	char* nameEnd = nameNumber;
	if(port>999)
		return ErrorInvalidPort;
	if(port>99)
		{
		*nameEnd++ = '0'+port/100;
		port %= 100;
		}
	if(port>9)
		{
		*nameEnd++ = '0'+port/10;
		port %= 10;
		}
	*nameEnd++ = '0'+port;
	*nameEnd = 0;

	// open port...
	hSerial = CreateFile(name, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if(hSerial==INVALID_HANDLE_VALUE)
		{
		switch(GetLastError())
			{
			case ERROR_FILE_NOT_FOUND:
				return ErrorInvalidPort;
			case ERROR_ACCESS_DENIED:
				return ErrorPortInUse;
			default:
				return Error();
			}
		}

#ifdef DEBUG_LOG
	strcpy(nameEnd,".log");
	DebugLog = fopen(nameNumber,"w+b");
#endif

	return 0;
	}


int WindowsSerialPort::Initialise(unsigned baud)
	{
	// flush port...
	if(!FlushFileBuffers(hSerial))
		return Error();
	if(!PurgeComm(hSerial, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR))
		return Error();

	// configure port...
	DCB dcb = {0};
	if(!GetCommState(hSerial, &dcb))
		return Error();
	dcb.BaudRate	= baud;
	dcb.ByteSize	= 8;
	dcb.StopBits	= ONESTOPBIT;
	dcb.Parity		= NOPARITY;
	if(!SetCommState(hSerial, &dcb))
		{
		if(GetLastError()==ERROR_INVALID_PARAMETER)
			return ErrorInvalidSettings;
		return Error();
		}

	// set timeouts to zero so read/writes return immediately...
	COMMTIMEOUTS timeouts = {0};
	timeouts.ReadIntervalTimeout		= MAXDWORD;
	timeouts.ReadTotalTimeoutConstant	= 0;
	timeouts.ReadTotalTimeoutMultiplier	= 0;
	timeouts.WriteTotalTimeoutConstant	= 0;
	timeouts.WriteTotalTimeoutMultiplier= 0;
	if(!SetCommTimeouts(hSerial, &timeouts))
		return Error();

	// flush port again...
	if(!PurgeComm(hSerial, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR))
		return Error();

	return 0;
	}


int WindowsSerialPort::Out(const uint8_t* data, size_t size, unsigned timeout)
	{
	DWORD bytes = 0;
	for(;;)
		{
		// read...
		if(!WriteFile(hSerial,data,size,&bytes,NULL))
			return Error(ErrorTransmitError);
		if(bytes)
			break; // end if any data was received
		if(timeout==0)
			break; // end if we have timed out

		// wait for 10 milliseconds...
		unsigned sleep = 10;
		if(sleep>timeout)
			sleep = timeout;
		timeout -= sleep;
		Sleep(sleep);
		}

#ifdef DEBUG_LOG
	DebugDump(">",data,bytes);
#endif

	return bytes;
	}


int WindowsSerialPort::In(uint8_t* data, size_t maxSize, unsigned timeout)
	{
	DWORD bytes = 0;
	for(;;)
		{
		// read...
		if(!ReadFile(hSerial,data,maxSize,&bytes,NULL))
			return Error(ErrorReceiveError);
		if(bytes)
			break; // end if any data was received
		if(timeout==0)
			break; // end if we have timed out

		// wait for 10 milliseconds...
		unsigned sleep = 10;
		if(sleep>timeout)
			sleep = timeout;
		timeout -= sleep;
		Sleep(sleep);
		}

#ifdef DEBUG_LOG
	DebugDump("<",data,bytes);
#endif

	return bytes;
	}


#ifdef DEBUG_LOG

void WindowsSerialPort::DebugDump(const char* prefix, const uint8_t* data, size_t size)
	{
	if(!DebugLog)
		return;

	size_t i=0;
	while(i<size)
		{
		fprintf(DebugLog,prefix);
		unsigned j;
		for(j=0; j<16 && i+j<size; j++)
			{
			fprintf(DebugLog," %02x",data[i+j]);
			}
		fprintf(DebugLog," ");
		for(unsigned k=0; k<j; k++)
			{
			uint8_t c = data[i+k];
			if(c<' '|| c>=0x7f)
				c = '.';
			fprintf(DebugLog,"%c",c);
			}
		fprintf(DebugLog,"\n");
		i += j;
		}
	}

#endif


void WindowsSerialPort::Close()
	{
	if(hSerial!=INVALID_HANDLE_VALUE)
		{
		CloseHandle(hSerial);
		hSerial = INVALID_HANDLE_VALUE;
		}
#ifdef DEBUG_LOG
	if(DebugLog)
		{
		fclose(DebugLog);
		DebugLog = 0;
		}
#endif
	}


inline WindowsSerialPort::WindowsSerialPort()
	: hSerial(0)
#ifdef DEBUG_LOG
	,DebugLog(0)
#endif
	{
	}


WindowsSerialPort::~WindowsSerialPort()
	{
	Close();
	}


SerialPort* SerialPort::New()
	{
	return new WindowsSerialPort;
	}


SerialPort::~SerialPort()
	{
	}


