/**
 * 
 * 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.activemq.ws.notification.impl.invoke;

import org.activemq.ws.notification.NotificationConsumer;
import org.activemq.ws.xmlbeans.notification.base.NotificationMessageHolderType;
import org.activemq.ws.xmlbeans.notification.base.NotifyDocument;
import org.apache.xmlbeans.XmlObject;
import org.codehaus.activesoap.RestClient;
import org.codehaus.activesoap.SoapClient;
import org.codehaus.activesoap.handler.xmlbeans.XMLBeansHelper;
import org.codehaus.activesoap.transport.TransportClient;
import org.codehaus.activesoap.transport.http.HttpTransportClient;

import java.net.MalformedURLException;

/**
 * Invokes a remote web service using <a href="http://activesoap.codehaus.org/">ActiveSOAP</a>
 * as a Web Services stack. This adapter can either invoke the endpoint as a NotificationConsumer
 * WSDL endpoint, or extract the inner messages inside the notification and invoke those
 *
 * @version $Revision: 1.1 $
 */
public class ActiveSOAPNotificationConsumer implements NotificationConsumer {

    private RestClient client;
    private boolean extractMessage = false;

    public ActiveSOAPNotificationConsumer(RestClient client) {
        this.client = client;
    }

    public static ActiveSOAPNotificationConsumer newRestInstance(TransportClient transport) {
        RestClient client = XMLBeansHelper.createRestClient(transport);
        return new ActiveSOAPNotificationConsumer(client);
    }

    public static ActiveSOAPNotificationConsumer newSoapInstance(TransportClient transport) {
        SoapClient client = XMLBeansHelper.createSoapClient(transport);
        return new ActiveSOAPNotificationConsumer(client);
    }

    public static ActiveSOAPNotificationConsumer newSoapHttpInstance(String url) throws MalformedURLException {
        return newSoapInstance(new HttpTransportClient(url));
    }

    public void notify(NotifyDocument notifyDocument) {
        if (!extractMessage) {
            try {
                client.invokeRequestReply(notifyDocument);
            }
            catch (Exception e) {
                throw new InvocationFailedException(notifyDocument, e);
            }
        }
        else {
            notifyMessages(notifyDocument);
        }
    }

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

    /**
     * Whether or not the web service should be invoked using the entire notification message
     * or should each message inside the message holder be extracted and invoked separately
     * as a web service invocation.
     *
     * i.e. is the endpoint invoked as a NotificationConsumer endpoint, or is it invoked
     * where the message itself is a SOAP envelope.
     */
    public boolean isExtractMessage() {
        return extractMessage;
    }

    public void setExtractMessage(boolean extractMessage) {
        this.extractMessage = extractMessage;
    }


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

    protected void notifyMessages(NotifyDocument notifyDocument) {
        NotifyDocument.Notify notify = notifyDocument.getNotify();
        NotificationMessageHolderType[] notificationMessageArray = notify.getNotificationMessageArray();
        for (int i = 0; i < notificationMessageArray.length; i++) {
            NotificationMessageHolderType holderType = notificationMessageArray[i];
            notifyMessage(holderType);
        }
    }

    protected void notifyMessage(NotificationMessageHolderType holderType) {
        if (holderType.getMessage() == null) {
            throw new InvocationFailedException(holderType, "No message available insider the message holder");
        }
        try {
            XmlObject message = holderType.getMessage();
            client.invokeRequestReply(message);
        }
        catch (Exception e) {
            throw new InvocationFailedException(holderType, e);
        }
    }

}
