#include <nsIInputStream.h>
#include <nsIDOMDocument.h>
#include <nsIDOMParser.h>
#include <nsNetUtil.h>
#include <nsIDOMElement.h>
#include <nsIDocument.h>
#include <nsfilestream.h>
#include <nsfilespec.h>
#include <nsDebug.h>
#include <nsLog.h>

NS_IMPL_LOG_ENABLED(TESTXML)
#define PRINTF NS_LOG_PRINTF(TESTXML)
#define FLUSH  NS_LOG_FLUSH(TESTXML)

void usage();

void usage() 
{
  PRINTF("\n");
  PRINTF("Usage:\n");
  PRINTF("  TestXMLParse xmlfile\n\n");
  PRINTF("      xmlfile  = A local XML URI (ie. d:\\file.xml)\n\n");

  return;
}

int main(int argc, char* argv[]) 
{
	nsresult rv = NS_OK;
	nsCOMPtr<nsIInputStream> pInputStream;
	PRUint32 uiContentLength;
	nsCOMPtr<nsIDOMParser> pDOMParser;
	nsCOMPtr<nsIDOMDocument> pDOMDocument;
	nsString filename;

    // Initialize XPCOM
    rv = NS_InitXPCOM(nsnull, nsnull);
    if (NS_FAILED(rv))
    {
        PRINTF("ERROR: XPCOM intialization error [%x].\n", rv);
        return -1;
    }

    nsComponentManager::AutoRegister(nsIComponentManager::NS_Startup, nsnull);

	if (argc > 1) 
	{
		filename.AppendWithConversion(argv[1]);
		nsFileSpec file(filename);
		if (file.Exists())
		{
			nsInputFileStream stream(file);
			pInputStream = stream.GetIStream();
			if (NS_SUCCEEDED(rv = pInputStream->Available(
					&uiContentLength)))
			{
				pDOMParser = do_CreateInstance( 
						NS_DOMPARSER_CONTRACTID, &rv);

				if (NS_SUCCEEDED(rv)) 
				{
					if (NS_SUCCEEDED(rv = 
							pDOMParser->ParseFromStream( 
							pInputStream, "UTF-8",
                            uiContentLength,
                            "text/xml",
                            getter_AddRefs(pDOMDocument))))
					{
						PRINTF("DOM parse of %s successful\n", 
								argv[1]);
					}
				}
				else 
				{
					PRINTF("DOM parse of %s NOT successful\n", 
							argv[1] );
				}
			}
			else 
			{
				PRINTF("do_CreateInstance of DOMParser failed for %s - %08X\n", 
						argv[1], rv );
			}
		}
		else 
		{
			PRINTF("pInputSteam->Available failed for %s - %08X\n",
					argv[1], rv );
		}
	}
    else 
	{
		PRINTF("NS_NewURI failed for %s - %08X\n", argv[1], rv );
    }

	if (pDOMDocument) 
	{
		nsCOMPtr<nsIDOMElement> element;
		pDOMDocument->GetDocumentElement(getter_AddRefs(element));
		nsAutoString tagName;
		if (element) 
		{
			element->GetTagName(tagName);
		}

		char *s = tagName.ToNewCString();
		PRINTF("Document element=\"%s\"\n",s);
		nsCRT::free(s);
		nsCOMPtr<nsIDocument> doc = do_QueryInterface(pDOMDocument);
		
		if (doc) 
		{
			nsCOMPtr<nsIURI> uri = dont_AddRef(doc->GetDocumentURL());
			nsXPIDLCString spec;
			uri->GetSpec(getter_Copies(spec));
			PRINTF("Document URI=\"%s\"\n",spec.get());
		}
	}

    NS_ShutdownXPCOM(nsnull);

	return 0;
}
