#include "stdafx.h"
#include "DownloadDlg.h"
#include "BindStatusCallback.h"
#include <shlwapi.h>

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

STDMETHODIMP CCallback::OnProgress ( ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR wszStatusText )
{

	static CString sIEStatusMsg;
	static TCHAR   szCustomStatusMsg [256];
	static TCHAR   szAmtDownloaded [256], szTotalSize [256];

	UNREFERENCED_PARAMETER(ulStatusCode);

	if ( 0 != g_fAbortDownload )
		return E_ABORT;

	if ( m_bUseTimeout  &&  CTime::GetCurrentTime() > m_timeToStop )
		return E_ABORT;

	if ( NULL != wszStatusText )
		sIEStatusMsg = wszStatusText;
	else
		sIEStatusMsg.Empty();

	StrFormatByteSize ( ulProgress, szAmtDownloaded, 256 );
	StrFormatByteSize ( ulProgressMax, szTotalSize, 256 );

	if ( 0 != ulProgressMax )
		wsprintf ( szCustomStatusMsg, _T("Downloaded %s of %s"), szAmtDownloaded, szTotalSize );
	else
		wsprintf ( szCustomStatusMsg, _T("Downloaded %s (total size unknown)"), szAmtDownloaded );

	if ( 0 != ulProgressMax )
		m_pDlg->ProgressUpdate ( sIEStatusMsg, szCustomStatusMsg, int( 100.0 * ulProgress / ulProgressMax) );
	else
		m_pDlg->ProgressUpdate ( sIEStatusMsg, szCustomStatusMsg, 0 );

 	return(NOERROR);
}

CCallback::CCallback()
{
    m_pbinding = NULL;
    m_pstm = NULL;
    m_cRef = 1;
    m_cbOld = 0;
	m_bUseTimeout = FALSE;
	m_pDlg = NULL;
}  

CCallback::~CCallback()
{
    if (m_pstm)
        m_pstm->Release();
    if (m_pbinding)
        m_pbinding->Release();
}  

STDMETHODIMP CCallback::QueryInterface(REFIID riid, void** ppv)
{ 
    *ppv = NULL;
    
    if (riid==IID_IUnknown || riid==IID_IBindStatusCallback)
        {
        *ppv = this;
        AddRef();
        return S_OK;
        }
    return E_NOINTERFACE;
}  

STDMETHODIMP CCallback::OnStartBinding(DWORD grfBSCOption, IBinding* pbinding)
{
	if(NULL != pbinding)
	{
		pbinding->AddRef();
		m_pbinding = pbinding;
	}

	return(NOERROR);
} 

STDMETHODIMP CCallback::OnStopBinding(HRESULT hrStatus, LPCWSTR pszError) 
{
	if(NULL != m_pbinding)
	{
		m_pbinding->Release();
		m_pbinding = NULL;
	}

	return(NOERROR);
}

STDMETHODIMP CCallback::GetPriority(LONG* pnPriority) 
{
	 return(NOERROR);
}  

STDMETHODIMP CCallback::OnLowResource(DWORD dwReserved)
{
 	 return(NOERROR);
}  

STDMETHODIMP CCallback::GetBindInfo(DWORD* pgrfBINDF, BINDINFO* pbindInfo)
{
	 return (NOERROR);
}

STDMETHODIMP CCallback::OnDataAvailable(DWORD grfBSCF, 
		DWORD dwSize, FORMATETC* pfmtetc, STGMEDIUM* pstgmed) 
{
	return(NOERROR);
}

STDMETHODIMP CCallback::OnObjectAvailable(REFIID riid, IUnknown* punk) 
{
	return(NOERROR);
}