/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log: CreateDOMDocument.cpp,v $
 * Revision 1.7  2001/10/26 11:55:46  tng
 * Nest entire test in an inner block for reference counting to recover all document storage when this block exits before XMLPlatformUtils::Terminate is called.
 *
 * Revision 1.6  2001/10/19 19:02:42  tng
 * [Bug 3909] return non-zero an exit code when error was encounted.
 * And other modification for consistent help display and return code across samples.
 *
 * Revision 1.5  2000/03/02 19:53:39  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.4  2000/02/06 07:47:17  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/01/19 00:17:50  rahulj
 * Added makefile for unix builds. Fixed the comments and usage
 * string.
 *
 * Revision 1.2  2000/01/18 23:57:35  rahulj
 * Now exploting C++ features to compact the sample code.
 *
 * Revision 1.1  2000/01/18 23:22:18  rahulj
 * Added new sample to illustrate how to create a DOM tree in
 * memory.
 *
 */

/*
 * This sample illustrates how you can create a DOM tree in memory.
 * It then prints the count of elements in the tree.
 */


//---------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <util/XMLString.hpp>
#include <parsers/DOMParser.hpp>
#include <dom/DOM.hpp>
#include <iostream.h>

#include "DOMTreeErrorReporter.hpp"
#include "PatientInfoXml.hpp"

//---------------------------------------------------------------------
// Constructors and Destructors
//---------------------------------------------------------------------
PatientInfoXml::PatientInfoXml()
{
}

PatientInfoXml::~PatientInfoXml()
{
}

//---------------------------------------------------------------------
// Other Methods
//---------------------------------------------------------------------
void PatientInfoXml::createDomFromData()
{
    // Initialize the XML4C2 system.
    try {
        XMLPlatformUtils::Initialize();
    } catch(const XMLException& toCatch) {
        //char *pMsg = XMLString::transcode(toCatch.getMessage());
        //cerr << "Error during Xerces-c Initialization.\n"
        //     << "  Exception message:"
        //     << pMsg;
        //delete pMsg;
        return;
    }

        DOM_DOMImplementation patientInfoImpl;

        // Create "patientInfo" document root

        DOM_Document doc = patientInfoImpl.createDocument(
            0,                    // Root element namespace URI.
            "patientInfo",        // Root element name
            DOM_DocumentType()    // Document type object (DTD).
        );

        DOM_Element rootElement = doc.getDocumentElement();

        // Create "patientID" node

        DOM_Element patientIdElement = doc.createElement("patientID");
        rootElement.appendChild(patientIdElement);
        DOM_Text patientIdValue = doc.createTextNode("123-45-6789");
        patientIdElement.appendChild(patientIdValue);

        // Create "patientName" node

        DOM_Element patientNameElement = 
            doc.createElement("patientName");
        rootElement.appendChild(patientNameElement);

        // Create "firstName" node

        DOM_Element firstNameElement = doc.createElement("firstName");
        patientNameElement.appendChild(firstNameElement);
        DOM_Text firstNameValue = doc.createTextNode("Jerry");
        firstNameElement.appendChild(firstNameValue);

        // Create "middleName" node

        DOM_Element middleNameElement = 
            doc.createElement("middleName");
        patientNameElement.appendChild(middleNameElement);
        DOM_Text middleNameValue = doc.createTextNode("Howard");
        middleNameElement.appendChild(middleNameValue);

        // Create "lastName" node

        DOM_Element lastNameElement = doc.createElement("lastName");
        patientNameElement.appendChild(lastNameElement);
        DOM_Text lastNameValue = doc.createTextNode("Jones");
        lastNameElement.appendChild(lastNameValue);

        // Create "dateOfBirth" node

        DOM_Element birthDateElement = 
            doc.createElement("dateOfBirth");
        rootElement.appendChild(birthDateElement);
        DOM_Text birthDateValue = doc.createTextNode("08121973");
        birthDateElement.appendChild(birthDateValue);

        // Create "gender" node

        DOM_Element genderElement = doc.createElement("gender");
        rootElement.appendChild(genderElement);
        DOM_Text genderValue = doc.createTextNode("male");
        genderElement.appendChild(genderValue);

        // Create "height" node

        DOM_Element heightElement = doc.createElement("height");
        rootElement.appendChild(heightElement);
        heightElement.setAttribute("units", "in");
        DOM_Text heightValue = doc.createTextNode("76");
        heightElement.appendChild(heightValue);

        // Create "weight" node

        DOM_Element weightElement = doc.createElement("weight");
        rootElement.appendChild(weightElement);
        weightElement.setAttribute("units", "lbs");
        DOM_Text weightValue = doc.createTextNode("205");
        weightElement.appendChild(weightValue);

    createXmlFromDom(doc);

    XMLPlatformUtils::Terminate();
    return;
}

// This method could be in a superclass

void PatientInfoXml::createDomFromXml(const char* pXmlFileUrl,
                                      bool useSchemaValidation)
{
    bool gDoNamespaces = false;
    bool gDoSchema = false;
    bool gDoSchemaFullChecking = false;
    DOMParser::ValSchemes gValScheme = DOMParser::Val_Never;

    if (useSchemaValidation) {
        gDoNamespaces = true;
        gDoSchema = true;
        gDoSchemaFullChecking = true;
        gValScheme = DOMParser::Val_Always;
    }

    // Initialize the XML4C2 system.
    try {
        XMLPlatformUtils::Initialize();
    } catch(const XMLException& toCatch) {
        //char *pMsg = XMLString::transcode(toCatch.getMessage());
        //cerr << "Error during Xerces-c Initialization.\n"
        //     << "  Exception message:"
        //     << pMsg;
        //delete pMsg;
        return;
    }

    //  Create our parser, then attach an error handler to the parser.
    //  The parser will call back to methods of the ErrorHandler if it
    //  discovers errors during the course of parsing the XML document.
    //
    DOMParser *parser = new DOMParser;
    parser->setValidationScheme(gValScheme);
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gDoSchemaFullChecking);
    //DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    //parser->setErrorHandler(errReporter);
    parser->setCreateEntityReferenceNodes(false);
    parser->setToCreateXMLDeclTypeNode(true);

    DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    parser->setErrorHandler(errReporter);

    //  Parse the XML file, catching any XML exceptions that might propogate
    //  out of it.
    //
    bool errorsOccured = false;
    try {
        parser->parse(pXmlFileUrl);
        int errorCount = parser->getErrorCount();
        if (errorCount > 0)
            errorsOccured = true;
    } catch (const XMLException& e) {
        //cerr << "An error occured during parsing\n   Message: "
        //     << DOMString(e.getMessage()) << endl;
        errorsOccured = true;
    } catch (const DOM_DOMException& e) {
        //cerr << "A DOM error occured during parsing\n   DOMException code: "
        //      << e.code << endl;
        errorsOccured = true;
    } catch (...) {
        //cerr << "An error occured during parsing\n " << endl;
        errorsOccured = true;
    }

    // If the parse was successful, output the document data from the DOM tree
    if (!errorsOccured)
    {
        DOM_Document doc = parser->getDocument();
        DOM_Element rootElement = doc.getDocumentElement();
        createXmlFromDom(rootElement);
    }

    delete parser;
    XMLPlatformUtils::Terminate();
    return;
}

//walk the DOM tree and print as u go

void PatientInfoXml::createXmlFromDom(DOM_Node node)
{
    char *pString;
    DOM_NamedNodeMap attributes;
    DOM_Node attribute;
    DOMString data;
    int aCount;
        int type = node.getNodeType();
        switch(type) {
            case DOM_Node::DOCUMENT_NODE:
                //System.out.println("<?xml version=\"1.0\" encoding=\""+
                //                  "UTF-8" + "\"?>");
                break;
            case DOM_Node::ELEMENT_NODE:
                // Translate for debugging
                data = node.getNodeName();
                pString = data.transcode();
                //System.out.print('<' + node.getNodeName() );
                attributes = node.getAttributes();
                if (attributes != NULL)
                {
                    aCount = attributes.getLength() ;
                    for ( int i = 0; i < aCount; i++ )
                    {
                        attribute = attributes.item(i);
                        //System.out.print(' '
                        //     + attribute.getNodeName()
                        //     + "=\""
                        //     + attribute.getNodeValue()
                        //     +  '"' );
                        // Translate for debugging
                        data = attribute.getNodeName();
                        pString = data.transcode();
                        data = attribute.getNodeValue();
                        pString = data.transcode();
                    }
                }
                //System.out.print('>');
                break;
            case DOM_Node::TEXT_NODE:
                //System.out.print(node.getNodeValue());
                // Translate for debugging
                data = node.getNodeValue();
                pString = data.transcode();
                break;
            case DOM_Node::ENTITY_REFERENCE_NODE:
                //System.out.print('&' + node.getNodeName() + ';' );
                break;
            case DOM_Node::CDATA_SECTION_NODE:
                //System.out.print( "<![CDATA["
                //        + node.getNodeValue()
                //        + "]]>" );
                break;
           case DOM_Node::PROCESSING_INSTRUCTION_NODE:
                //System.out.print("<?"
                //    + node.getNodeName() ) ;
                data = node.getNodeValue();
                if ( data != NULL && data.length() > 0 ) {
                //    System.out.print(' ');
                //    System.out.print(data);
                }
                //System.out.println("?>");
                break;
            default:
                ;
        }//end of switch
              
        //recurse
        for(DOM_Node child = node.getFirstChild(); child != NULL; child = child.getNextSibling())
        {
            createXmlFromDom(child);
        }
        
        //without this the ending tags will miss
        if ( type == DOM_Node::ELEMENT_NODE )
        {
            //System.out.print("</" + node.getNodeName() + ">");
        }

    }//end of walk

