// SimpleHTTPFile.cpp: implementation of the CSimpleHTTPFile class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ryllogin.h"
#include "SimpleHTTPFile.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSimpleHTTPFile::CSimpleHTTPFile()
{
	m_hIntSession = NULL;
}

CSimpleHTTPFile::~CSimpleHTTPFile()
{
	if( NULL != m_hIntSession )
	{
		InternetCloseHandle( m_hIntSession );
	}
}


void CSimpleHTTPFile::Close()
{
	if( NULL != m_hIntSession )
	{
		InternetCloseHandle( m_hIntSession );
	}
}


bool CSimpleHTTPFile::Init()
{
	m_hIntSession = InternetOpen( NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL );
	
	if( m_hIntSession == NULL )
	{
		MessageBox( NULL, "Failed to establish network connection.", 0, 0 );
		return false;
	}

	return true;
}



bool CSimpleHTTPFile::TransferFile( const TCHAR* strServerFilename, const TCHAR* strClientFilename )
{
	HINTERNET hSession = InternetOpenUrl( m_hIntSession, strServerFilename, NULL, 0, INTERNET_FLAG_HYPERLINK, 0 );

	if( hSession == NULL )
	{	
		CString strError;
		strError.Format( " Failed to locate file on server : %s", strServerFilename );
		MessageBox( NULL, strError, 0, 0 );
		return false;
	}

	FILE *fp = fopen( strClientFilename, "wb" );
	if( NULL == fp )
	{
		return false;
	}

	DWORD dwBytesRead = 0;
	char httpBuff[1024];

	while( InternetReadFile( hSession, httpBuff, 1024, &dwBytesRead ) && dwBytesRead != 0 )
	{
		fwrite( httpBuff, dwBytesRead, 1, fp );
	}

	fclose( fp );

	InternetCloseHandle( hSession );
	
	return true;
}
