// MyBho.cpp : Implementation of CMyBho
#include "stdafx.h"
#include "BhoTest.h"
#include "MyBho.h"
#include <ExDispID.h>
#include <comdef.h>
#include <stdio.h>

#pragma data_seg (".HookSection")		
int g_count = 0;
#pragma data_seg ()
#pragma comment(linker, "/section:.HookSection,rws")

//Globals
HHOOK g_hHook2 = NULL;
BOOL g_show = FALSE;
UINT_PTR g_timerevent;

CComQIPtr<IWebBrowser2, &IID_IWebBrowser2> g_spWebBrowser2;
BOOL shown = FALSE;

void Show();

/////////////////////////////////////////////////////////////////////////////
// CMyBho
VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent,DWORD dwTime);

// IOleObjectWithSite Methods
STDMETHODIMP CMyBho::SetSite(IUnknown *pUnkSite)
// Connect to browser
{
	if (pUnkSite != NULL)
	{
		// Query pUnkSite for the IWebBrowser2 interface.
		m_spWebBrowser2 = pUnkSite;
		
		if (m_spWebBrowser2)
		{			
			// Connect to the browser in order to handle events.
			if (!ManageConnection(Advise))
			{
				MessageBox(NULL,"Error","Error",MB_ICONERROR);
			}
				
		}	
		
		// Set the mouse hook
		g_hHook2 = SetWindowsHookEx(WH_MOUSE,
								   reinterpret_cast<HOOKPROC>(IEMouseProc),
								   NULL,
								   GetCurrentThreadId());
		
	}
	
	return S_OK;
}


BOOL CMyBho::ManageConnection(enum AdviseAction action)
// Setup advise sink
{
	if (!m_spWebBrowser2)
		return S_OK;
	
	HRESULT hr;
	
	CComQIPtr<IConnectionPointContainer, &IID_IConnectionPointContainer> spCPContainer(m_spWebBrowser2);
	
	if (spCPContainer != NULL)
	{
		CComPtr<IConnectionPoint> spConnectionPoint;
		
		hr = spCPContainer->FindConnectionPoint(DIID_DWebBrowserEvents2, &spConnectionPoint);
		if (SUCCEEDED(hr))
		{
			if (action == Advise)
				// Advise the client site that we want to sink events
				hr = spConnectionPoint->Advise((IDispatch*)this, &m_dwCookie);
			else
				// Remove us from the list of active sinks
				hr = spConnectionPoint->Unadvise(m_dwCookie);
		}
	}
	
	return (SUCCEEDED(hr));
}



// IDispatch Methods
STDMETHODIMP CMyBho::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,
								  DISPPARAMS* pDispParams, VARIANT* pvarResult,
								  EXCEPINFO*  pExcepInfo,  UINT* puArgErr)								  
{
	if (!pDispParams)
		return E_INVALIDARG;
	
	CComPtr<IDispatch>	spDisp;
	//HRESULT	 hr;
	USES_CONVERSION;

	switch (dispidMember)
	{
	case DISPID_DOCUMENTCOMPLETE:
		m_spWebBrowser2 = pDispParams->rgvarg[1].pdispVal;
		
		{
			if(shown == FALSE)//check if the html has been modified
			{
				g_spWebBrowser2 = m_spWebBrowser2;	//store the web browser interface			
			}

			CComPtr<IDispatch> pDisp;
			HRESULT hr = m_spWebBrowser2->get_Document(&pDisp);
			if (FAILED(hr))
				break;

			CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> spHTML;
			spHTML = pDisp;

			if (spHTML)
			{

				// Get the BODY object
				CComPtr<IHTMLElement> m_pBody;
				hr = spHTML->get_body(&m_pBody); 
				if (FAILED(hr))
					break;
				
				// Get the HTML text
				BSTR bstrHTMLText;
				hr = m_pBody->get_outerHTML(&bstrHTMLText); 
				if (FAILED(hr))
					break;				

				// Convert the text from Unicode to ANSI
				LPTSTR psz = new TCHAR[1 + SysStringLen(bstrHTMLText)];
				lstrcpy(psz, OLE2T(bstrHTMLText));

				//The strings to be used in the log file to assign start and end positions to the logs
				LPTSTR s1 = "\r\nBEGIN---------------------------------------------------\r\n";
				LPTSTR s2 = "\r\nEND-----------------------------------------------------\r\n";

				CComBSTR url;
				try
				{
					m_spWebBrowser2->get_LocationURL(&url);
				}
				catch(...)
				{
				}
				
				if(url == "about:blank")
				{

				}
				else
				{
					
				}

				delete [] psz;
			}

		}

		break;
		
	case DISPID_ONQUIT:
		ManageConnection(Unadvise);		
	
		UnhookWindowsHookEx(g_hHook2);//remove mouse hook
		break;
		
	default:
		break;
	}
	
	return S_OK;
}



/////////////////////////////////////////////////////////////////////////////
// IEMouseProc - Mouse hook procedure. It is necessarily a static
// member of the class.

LRESULT CALLBACK CMyBho::IEMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{	
	if(wParam == WM_RBUTTONDOWN  )
	{
		LRESULT l = CallNextHookEx(g_hHook2, nCode, wParam, lParam);
		//If the right mouse is clicked we start a new timer of 300 ms
		if(g_count == 0)
			g_timerevent = SetTimer(NULL,0,300,TimerProc);
		return l;
	}
	return CallNextHookEx(g_hHook2, nCode, wParam, lParam);
		
	
}

void Show()
{
	USES_CONVERSION;

	CComPtr<IDispatch> pDisp;
	HRESULT hr = g_spWebBrowser2->get_Document(&pDisp);
	if (FAILED(hr))
		return;

	bool bf1 = true;

	CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> spHTML;
	spHTML = pDisp;
	if (spHTML)
	{
		// Get the BODY object
		CComPtr<IHTMLElement> m_pBody;
		hr = spHTML->get_body(&m_pBody); 
		if (FAILED(hr))
			return;

		CComPtr<IHTMLElementCollection> pAll;
		hr = spHTML->get_all(&pAll);
		if(SUCCEEDED(hr))
		{
			long lNum, lElemIndex;
			pAll->get_length(&lNum);
			
			for (lElemIndex = 0; lElemIndex < lNum; lElemIndex++)
			{
				CComQIPtr<IHTMLElement, &IID_IHTMLElement> spInputElem;
				CComPtr<IDispatch>	spDisp;
				spDisp = NULL;

				_variant_t	vElemName(lElemIndex);
				_variant_t	vElemIndex;

				// Get element
				hr = pAll->item(vElemName, vElemIndex, &spDisp);
				spInputElem = spDisp;
				
				if (SUCCEEDED(hr))
				{
					BSTR str;
					hr = spInputElem->get_outerHTML(&str);

					if (SUCCEEDED(hr))
					{
						LPTSTR psz1 = new TCHAR[1 + SysStringLen(str)];
						if(SysStringLen(str) < 512)
						{
							lstrcpy(psz1, OLE2T(str));
							CComBSTR strname;
							spInputElem->get_tagName(&strname);
							

							if(strname == "SPAN")
							{
								CComBSTR strname = "href";
								CComVariant curvalue;
								hr = spInputElem->getAttribute(strname,0,&curvalue);
								
							}//if								
						}//if
						delete[] psz1;
					}//if
				}//if				
			}//for
		}//if

		if(bf1)
		{
			if(g_count > 10)
			{
				//after 10 attempts we decide not to search this page again
				g_count = 0;
			}
			else
			{
				//we re-start the timer if the replacement has not been done already
				g_timerevent = SetTimer(NULL,0,300,TimerProc);
			}
		}


		
		
	}
}

VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent,DWORD dwTime)
{
	g_count++;
	//Kill the timer because we do not want the timer to be called again until Show has exited
	KillTimer(NULL,g_timerevent);
	Show();
}