#include "StdAfx.h"
#include ".\submitter.h"
#include "ArticleManager.h"
#include <mshtml.h>
#include <atlbase.h>
#include <comdef.h>
#include <atlcom.h>
#include <atlwin.h>

IWebBrowser2* RunIe( bool show /*=true*/)
{
  IWebBrowser2 *pIE = 0;
  //CoInitialize( NULL );
  // Create an instance of Internet Explorer
  HRESULT hr = CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER, IID_IWebBrowser2, (void**)&pIE);
  if (SUCCEEDED(hr) && show)
    pIE->put_Visible(VARIANT_TRUE);
  return pIE;
}


CSubmitter::CSubmitter(void)
{
	mBrowser = 0;
	mArticle = 0;
	mSite = 0;
	mManager = 0;
}

CSubmitter::~CSubmitter(void)
{
}


void CSubmitter::Submit( CArticleManager* manager, CArticle* article, CSite* site )
{
	USES_CONVERSION;

	mManager = manager;
	mBrowser = RunIe(1);
	mArticle = article;
	mSite = site;


	if (!mBrowser)
		return;

	mBrowserUnk = 0;
	mBrowser->QueryInterface( IID_IUnknown, (void**)&mBrowserUnk);

	if (!mBrowserUnk)
		return;

	//hook the event sink
    HRESULT hr = mBrowserUnk->QueryInterface(IID_IWebBrowser2, (void**)&mBrowser);

    if (FAILED(hr))
        return;

    hr = CComObject<CEventSink>::CreateInstance(&mSink);

    if (FAILED(hr))
        return;

	mSink->AddRef();

	mSink->mSubmitter = this;

    hr = AtlAdvise( mBrowserUnk, mSink->GetUnknown(),
                   DIID_DWebBrowserEvents2, &m_dwCookie);





	//navigate to the initial URL
	_variant_t varURL = A2W( site->getURL());
	_variant_t varEmpty;
	HRESULT hr2 = mBrowser->Navigate2(&varURL, &varEmpty, &varEmpty, &varEmpty, &varEmpty);

	if (hr2 != S_OK)
		return;
}



//event sink
STDMETHODIMP CEventSink::GetTypeInfoCount(UINT* pctinfo)
{
    return E_NOTIMPL;
}

STDMETHODIMP CEventSink::GetTypeInfo(UINT itinfo, LCID lcid,
                                     ITypeInfo** pptinfo)
{
    return E_NOTIMPL;
}

STDMETHODIMP CEventSink::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames,
                                       UINT cNames, LCID lcid,
                                       DISPID* rgdispid)
{
    return E_NOTIMPL;
}

STDMETHODIMP CEventSink::Invoke(DISPID dispid, REFIID riid, LCID lcid,
                                WORD wFlags, DISPPARAMS* pdispparams,
                                VARIANT* pvarResult, EXCEPINFO* pexcepinfo,
                                UINT* puArgErr)
{
    if (dispid != DISPID_DOCUMENTCOMPLETE)
        return S_OK;

    if (pdispparams->cArgs != 2)
        return S_OK;

    if (pdispparams->rgvarg[0].vt != (VT_VARIANT | VT_BYREF))
        return S_OK;

    if (pdispparams->rgvarg[1].vt != VT_DISPATCH)
        return S_OK;

	mSubmitter->ProcessDocument( pdispparams->rgvarg[1].pdispVal );

    return S_OK;
}

void CSubmitter::ProcessDoc( IHTMLDocument3* doc )
{
	IHTMLElementCollection* pColl = 0;
	doc->getElementsByTagName( L"input", &pColl );

	if (!pColl)
		return;

	long len = 0;
	pColl->get_length( &len );

	for (int a = 0; a < len; a++)
	{
		VARIANT param;
		param.vt = VT_I4;
		param.intVal = a;

		VARIANT var;
		var.vt = VT_INT;
		var.intVal = 0;

		IDispatch* elemdisp = 0;
		HRESULT hr = pColl->item( param, var, (IDispatch**)&elemdisp);

		IHTMLElement* element = 0;
		if (!elemdisp)
			return;
		elemdisp->QueryInterface( IID_IHTMLElement, (void**)&element );

		if (element)
		{
			VARIANT val;
			element->getAttribute( L"name", 0, &val );
		}
	}
}

void CSubmitter::ProcessDocument( IDispatch* pdisp )
{
	USES_CONVERSION;

	IHTMLDocument3* pDocument3 = NULL;
	IHTMLDocument2* pDocument  = NULL;
	IHTMLElement2* pElement2   = NULL;
	IHTMLElement* pElement     = NULL;
	IViewObject2* pViewObject  = NULL;
	IDispatch* pDispatch       = NULL;
	IDispatch* pWebBrowserDisp = NULL;


	HRESULT hr = mBrowserUnk->QueryInterface(IID_IDispatch, (void**)&pWebBrowserDisp);
	
	if (FAILED(hr))
		return;

	if (pWebBrowserDisp != pdisp)
	{
		pWebBrowserDisp->Release();
		return;
	}

	hr = mBrowser->get_Document(&pDispatch);

	if (FAILED(hr))
		return;

	hr = pDispatch->QueryInterface(IID_IHTMLDocument2, (void**)&pDocument);

	if (FAILED(hr))
		return;

	hr = pDocument->get_body(&pElement);

	if (FAILED(hr))
		return;

	hr = pDispatch->QueryInterface(IID_IHTMLDocument3, (void**)&pDocument3);

	if (FAILED(hr))
		return;

	IHTMLElementCollection* pColl = 0;
	
	pDocument->get_all( &pColl );

	IHTMLFormElement* form = 0;

	if (pColl)
	{
		long len = 0;
		pColl->get_length( &len );

		for (int a = 0; a < len; a++)
		{
			VARIANT param;
			param.vt = VT_I4;
			param.intVal = a;

			VARIANT var;
			var.vt = VT_INT;
			var.intVal = 0;

			IDispatch* elemdisp = 0;
			HRESULT hr = pColl->item( param, var, (IDispatch**)&elemdisp);

			IHTMLElement* element = 0;
			if (!elemdisp)
				return;
			
			elemdisp->QueryInterface( IID_IHTMLElement, (void**)&element );

			if (element)
			{
				BSTR tagname;
				element->get_tagName( &tagname );

				if (!wcscmp( tagname, L"INPUT") )
				{
					IHTMLInputElement* inputelem = 0;
					element->QueryInterface( IID_IHTMLInputElement, (void**)&inputelem );
					if (inputelem)
					{
						BSTR name;
						inputelem->get_name( &name );
						if (name)
						{
							if (!wcsicmp( name, A2W( mSite->mFormFirstName )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mFirstName ) );
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormLastName )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mLastName ));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormEmail )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mEmail ) );
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormURL)))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mURL ));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormCompany)))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mCompany));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormTitle)))
							{
								BSTR namestr = SysAllocString( A2W( mArticle->getTitle()));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormArticle)))
							{
								BSTR namestr = SysAllocString( A2W( mArticle->getText()));
								inputelem->put_value( namestr );
								inputelem->get_form( &form );
							}
						}
					}
				}
				else if (!wcscmp( tagname, L"TEXTAREA") )
				{
					IHTMLTextAreaElement* inputelem = 0;
					element->QueryInterface( IID_IHTMLTextAreaElement, (void**)&inputelem );
					if (inputelem)
					{
						BSTR name;
						inputelem->get_name( &name );
						if (name)
						{
							if (!wcsicmp( name, A2W( mSite->mFormFirstName )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mFirstName ) );
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormLastName )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mLastName ));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormEmail )))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mEmail ) );
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormURL)))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mURL ));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormCompany)))
							{
								BSTR namestr = SysAllocString( A2W( mManager->mCompany));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormTitle)))
							{
								BSTR namestr = SysAllocString( A2W( mArticle->getTitle()));
								inputelem->put_value( namestr );
							}
							else if (!wcsicmp( name, A2W( mSite->mFormArticle)))
							{
								BSTR namestr = SysAllocString( A2W( mArticle->getText()));
								inputelem->put_value( namestr );
								inputelem->get_form( &form );
							}
						}
					}
				}
			}
		}
	}

	if (form)
	{
		form->submit();
	}

//	ProcessDoc( pDocument3 );

	if (pDocument3)
		pDocument3->Release();
	if (pDocument)
		pDocument->Release();
	if (pElement2)
		pElement2->Release();
	if (pElement)
		pElement->Release();
	if (pDispatch)
		pDispatch->Release();

	pWebBrowserDisp->Release();		

	//close down
	mBrowser->Quit();
	mBrowser->Release();
	mManager->mBrowsing = 0;
//	mDone = 1;
}