/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.jbi.serviceengine.bridge.transport;

import com.sun.enterprise.jbi.serviceengine.comm.MessageExchangeTransport;
import com.sun.enterprise.jbi.serviceengine.comm.MessageExchangeTransportFactory;
import com.sun.enterprise.jbi.serviceengine.comm.UnWrappedMessage;
import com.sun.enterprise.jbi.serviceengine.core.JavaEEServiceEngineContext;
import com.sun.enterprise.jbi.serviceengine.util.JBIConstants;
import com.sun.enterprise.jbi.serviceengine.util.soap.EndpointMetaData;
import com.sun.xml.ws.api.message.Message;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.ExchangeStatus;
import javax.xml.namespace.QName;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessageExchangeFactory;

/**
 *
 * @author Manisha Umbarje
 */
public class NMRClientConnection {
    
    //private QName svcQName;
    private boolean oneWay;
    private URL wsdlLocation;
    private QName service;
    private String endpointName;
    
    private QName operation;
    private MessageExchange me = null;
    private MessageExchangeTransport meTransport;
    
    private static ConcurrentHashMap<String, EndpointMetaData> emdCache =
            new ConcurrentHashMap<String, EndpointMetaData>(11,0.75f,4);
    
    public NMRClientConnection(URL wsdlLocation,
            QName service,
            String endpointName,
            QName operation,
            boolean oneWay) {
        this.wsdlLocation = wsdlLocation;
        this.service = service;
        this.endpointName = endpointName;
        this.operation = operation;
        setOneWay(oneWay);
    }
    
    public void setOneWay(boolean oneWay) {
        this.oneWay = oneWay;
    }
    
    public void initialize() {
        try {
            DeliveryChannel channel =
                    JavaEEServiceEngineContext.getInstance(). getDeliveryChannel();
            // Create MessageExchange
            MessageExchangeFactory factory =
                    channel.createExchangeFactoryForService(service);
            me =  oneWay ? factory.createInOnlyExchange() : factory.createInOutExchange();
            me.setService(service);
            ComponentContext context = JavaEEServiceEngineContext.getInstance().getJBIContext();
            me.setEndpoint(context.getEndpoint(service, endpointName));
            me.setOperation(operation);
            meTransport = MessageExchangeTransportFactory.getHandler(me);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
    
    /**
     * Get the EndpointMetaData from the cache if running in production clientCache.
     * Otherwise, return a new EndpointMetaData.
     */
    private EndpointMetaData getEndpointMetaData() {
        String clientCache = System.getProperty(JBIConstants.CLIENT_CACHE);
        if("false".equalsIgnoreCase(clientCache)) {
            return createEndpointMetaData();
        } else {
            String key = wsdlLocation.toString();
            EndpointMetaData emd = emdCache.get(key);
            if(emd == null) {
                emd = createEndpointMetaData();
                emdCache.put(key, emd);
            }
            return emd;
        }
    }
    
    private EndpointMetaData createEndpointMetaData() {
        EndpointMetaData emd = new EndpointMetaData(wsdlLocation, service, endpointName);
        emd.resolve();
        return emd;
    }
    
    public void sendRequest(Message abstractMessage) {
        meTransport.send(abstractMessage, getEndpointMetaData());
    }
    
    public UnWrappedMessage receiveResponse() {
        return meTransport.receive(getEndpointMetaData());
    }
    
    public void sendStatus() {
        if(me.getStatus().equals(ExchangeStatus.ACTIVE)) {
            meTransport.sendStatus(ExchangeStatus.DONE);
        }
    }
    
}
