/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.ws.soap;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.util.StreamReaderDelegate;


/**
 * A simple class which parsers the SOAP envelope using StAX
 * then delegates the processing of the
 * body to a separate strategy, which will typically be XMLBeans but could be anything.
 *
 * @version $Revision: 1.1 $
 */
public class EnvelopeParser {
    private XMLStreamReader in;
    private XmlObject body;

    public EnvelopeParser(XMLStreamReader in) {
        this.in = in;
    }

    public void close() throws XMLStreamException {
        in.close();
    }

    public void parse() throws XMLStreamException, XmlException {
        body = null;
        skipToElementStart("Envelope");

        skipToElementStart("Header");
        processHeaders();

        skipToElementStart("Body");
        processBody();
    }

    // Properties
    //-------------------------------------------------------------------------

    /**
     * Returns the body of the SOAP request converted to the native object
     * if available or null if the body was not parsed
     */
    public XmlObject getBody() {
        return body;
    }

    // Implementation methods
    //-------------------------------------------------------------------------

    protected void processHeaders() throws XMLStreamException {
        QName name = in.getName();

        skipToEndOfTag(name);
    }

    protected void processBody() throws XmlException {
        // lets hard code for now
        System.out.println("About to subscribe the body");

        QName bodyName = in.getName();

        StreamReaderDelegate filter = new SubDocumentXMLStreamFilter(bodyName, in);

        body = XmlObject.Factory.parse(filter);

        handleBody(body);
    }

    protected void handleBody(XmlObject body) {
        System.out.println("Got body: " + body);
    }

    protected void skipToEndOfTag(QName name) throws XMLStreamException {
        while (in.hasNext()) {
            in.next();

            if (in.isEndElement()) {
                QName actual = in.getName();
                if (actual != null && actual.equals(name)) {
                    return;
                }
            }
        }
        throw new XMLStreamException("Expected element '" + name + " but document finished");
    }

    protected XMLEvent skipToElementStart(String expected) throws XMLStreamException {
        while (in.hasNext()) {
            in.next();
            if (in.isStartElement()) {
                break;
            }
        }
        if (!in.isStartElement()) {
            throw new XMLStreamException("Expected element '" + expected + " but document finished");
        }
        String actual = in.getLocalName();
        if (!expected.equals(actual)) {
            throw new XMLStreamException("Expected element '" + expected + "' but got '" + actual + "' at: " + in.getLocation());
        }
        return null;
    }

}
