package org.ow2.jonas.ws.axis2.test.handlers;


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPElement;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class GreeterSOAPHandler implements SOAPHandler<SOAPMessageContext> {

    @Resource
    WebServiceContext context = null;

    //@Resource(name = "greeting")
    //private String greeting;

    @PostConstruct
    public void init() {
        System.out.println(this + " init: " + context);
    }

    @PreDestroy
    public void destroy() {
        System.out.println(this + " destroy");
    }

    public void init(final Map<String, Object> config) {
    }

    public boolean handleFault(final SOAPMessageContext context) {
        System.out.println(this + " handleFault");
        return true;
    }

    public void close(final MessageContext context) {
        System.out.println("CLOSE in SOAPHandler");
    }

    public boolean handleMessage(final SOAPMessageContext context) {
        System.out.println("GREATERSOAPHandler HandleMessage");
        System.out.println(context == null);
        System.out.println(context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY));
        return true;
    }

    private SOAPElement findElement(final SOAPElement element, final String name) {
        Iterator<?> iter = element.getChildElements();
        while(iter.hasNext()) {
            Node child = (Node)iter.next();
            if (child instanceof SOAPElement) {
                SOAPElement childEl = (SOAPElement)child;
                if (name.equals(childEl.getElementName().getLocalName())) {
                    return childEl;
                } else {
                    return findElement(childEl, name);
                }
            }
        }
        return null;
    }

    public Set<QName> getHeaders() {
        System.out.println(this + " getHeaders");
        return new TreeSet<QName>();
    }

}
