#include <common/openfile.hpp>

FileHandle::~FileHandle()
{
  close();
}

SystemTime FileHandle::creationTime(void)const
{
	FileTime creationTimeDate;
	::GetFileTime(mhFileHandle,&((FILETIME&)creationTimeDate),0,0);
	return creationTimeDate;
}

SystemTime FileHandle::lastAccessTime(void)const
{
	FileTime lastAccessTimeDate;
	::GetFileTime(mhFileHandle,0,&((FILETIME&)lastAccessTimeDate),0);
	return lastAccessTimeDate;
}

SystemTime FileHandle::lastModifyTime(void)const
{
	FileTime lastModifyTimeDate;
	::GetFileTime(mhFileHandle,0,0,&((FILETIME&)lastModifyTimeDate));
	return lastModifyTimeDate;
}

DWORD FileHandle::getLine(String &lineString)const
{
  int granularity(1024);
	int blockLength(granularity);
	BYTE charByte;
	BYTE *ptrLine;
	WORD bytesRead(0);

	lineString.reserve(blockLength);
	ptrLine=(BYTE*)(char*)lineString;
	while(TRUE)
	{
	  if(!read(charByte))break;
		if(bytesRead>=blockLength-1)
		{
		  *ptrLine=0;
			String tmpString(lineString);
			int nextIndex(ptrLine-(BYTE*)(char*)lineString);
			lineString.reserve(blockLength+granularity);
			::memcpy((char*)lineString,(char*)tmpString,blockLength);
			blockLength+=granularity;
			ptrLine=(BYTE*)(char*)lineString+nextIndex;
		}
		if(CarriageReturn==charByte)
		{
		  if(!read(charByte))break;
			if(LineFeed==charByte)
			{
			  *ptrLine=0;
				return TRUE;
			}
		}
		else if(LineFeed==charByte)
		{
		  *ptrLine=0;
			return TRUE;
		}
		else if(NullChar==charByte)
		{
		  *ptrLine++=0;
			return bytesRead;
		}
		else if(TabChar==charByte)continue;
		else 
		{
		  *ptrLine++=charByte;
			bytesRead++;
		}
	}
	return bytesRead;
}

/*
DWORD FileHandle::getLine(String &lineString)const
{
  int granularity(1024);
	int blockLength(granularity);
	BYTE charByte;
	BYTE *ptrLine;
	WORD bytesRead(0);

	lineString.reserve(blockLength);
	ptrLine=(BYTE*)(char*)lineString;
	while(TRUE)
	{
	  if(!read(charByte))break;
		if(bytesRead>=blockLength-1)
		{
		  *ptrLine=0;
			String tmpString(lineString);
			int nextIndex(ptrLine-(BYTE*)(char*)lineString);
			lineString.reserve(blockLength+granularity);
			::memcpy((char*)lineString,(char*)tmpString,blockLength);
			blockLength+=granularity;
			ptrLine=(BYTE*)(char*)lineString+nextIndex;
		}
		if(CarriageReturn==charByte)
		{
		  if(!read(charByte))break;
			bytesRead++;
			if(LineFeed==charByte)
			{
			  bytesRead++;
			  *ptrLine=0;
				return bytesRead;
			}
		}
		else if(NullChar==charByte)
		{
		  *ptrLine++=0;
			return bytesRead;
		}
		else 
		{
		  *ptrLine++=charByte;
			bytesRead++;
		}
	}
	return bytesRead;
}
*/
