#include "Mix/Tool/Win32/Core/File/InputStream.h"

namespace Mix{ namespace Tool{ namespace Win32{ namespace File{

InputStream::InputStream( void ) :
m_hFile( INVALID_HANDLE_VALUE ),
m_Pos( 0 ),
m_Size( 0 )
{
}

InputStream::~InputStream( void )
{
	Close();
}

bool InputStream::Open( const wchar_t* pFileName )
{
	if( ( pFileName == NULL ) ||
		( ::wcslen( pFileName ) == 0 ) )
	{
		return false;
	}

	Close();

	m_hFile = ::CreateFile( pFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	if( m_hFile == INVALID_HANDLE_VALUE )
	{
		return false;
	}

	m_Size = ::GetFileSize( m_hFile, NULL );
	if( m_Size == 0xFFFFFFFF )
	{
		Close();
		return false;
	}

	return true;
}

void InputStream::Close( void )
{
	if( m_hFile != INVALID_HANDLE_VALUE )
	{
		::CloseHandle( m_hFile );
		m_hFile = INVALID_HANDLE_VALUE;
	}

	m_Pos = 0;
	m_Size = 0;
}

bool InputStream::Read( void* pData, unsigned int dataSize )
{
	if( m_hFile == INVALID_HANDLE_VALUE )
	{
		return false;
	}

	DWORD readSize = 0;

	if( ( ::ReadFile( m_hFile, pData, dataSize, &readSize, NULL ) == FALSE ) ||
		( readSize != dataSize ) )
	{
		return false;
	}

	m_Pos += readSize;

	return true;
}

void InputStream::Skip( unsigned int size )
{
	if( m_hFile == INVALID_HANDLE_VALUE )
	{
		return;
	}

	DWORD pos = ::SetFilePointer( m_hFile, size, NULL, FILE_CURRENT );
	if( pos != INVALID_SET_FILE_POINTER )
	{
		m_Pos = pos;
	}
}

unsigned int InputStream::GetPosition( void ) const
{
	return m_Pos;
}

unsigned int InputStream::GetSize( void ) const
{
	return m_Size;
}

Mix::Tool::Win32::Object::TYPE InputStream::GetType( void ) const
{
	return Mix::Tool::Win32::Object::FILE__INPUT_STREAM;
}

}}}}
