/*
 * 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.
 */

/*
 * Copyright 2004-2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

package com.sun.enterprise.iiop;

import com.sun.enterprise.util.Utility;

import org.omg.IOP.Codec;
import org.omg.IOP.ServiceContext;
import org.omg.IOP.TaggedComponent;

import org.omg.CORBA.*;
import org.omg.PortableInterceptor.*;

import java.util.logging.Level;

/**
 * This is the implementation of the JTS PI-based client/server interceptor.
 * This will be called during request/reply invocation path.
 * 
 */
public class SFSBClientRequestInterceptor
    extends SFSBAbstractInterceptor
    implements ClientRequestInterceptor {

    public SFSBClientRequestInterceptor(Codec codec) {
        super("com.sun.enterprise.iiop.SFSBClientRequestInterceptor", codec);
    }

    // implementation of the ClientInterceptor interface.

    public void send_request(ClientRequestInfo ri) throws ForwardRequest {
        if (doesSFSBVersionPolicyExist(ri)) {
            EJBTargetKeyInfo oidInfo = new EJBTargetKeyInfo(ri
                    .effective_target());
            if (_logger.isLoggable(Level.FINE)) {
                _logger.log(Level.FINE, "**SFSBClientInterceptor.send_request...: "
                    + ri.operation() + " " + oidInfo);
            }
            
            try {
                //Any anyData = ri.get_slot(getSlotID());
                long version = SFSBClientVersionManager.getClientVersion(oidInfo.getContainerId(),
                        oidInfo.getInstanceKey());
                //version = ++versionCounter;
                //anyData.insert_longlong(version);
                byte[] data = new byte[8];
                Utility.longToBytes(version, data, 0);
                ri.add_request_service_context(new ServiceContext(
                        SFSBVersionConstants.SFSB_VERSION_SERVICE_CONTEXT_ID, data),
                        false);
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "**SFSBClientInterceptor.send_request. anyData: " + version);
                }
            } catch (Exception e) {
                //TODO::
            }
        }

    }

    public void send_poll(ClientRequestInfo ri) {
        // do nothing.
    }

    private void receiveSFSBVersionNumber(String callName, ClientRequestInfo ri) {
        if (doesSFSBVersionPolicyExist(ri)) {
            EJBTargetKeyInfo oidInfo = new EJBTargetKeyInfo(ri.effective_target());
            ServiceContext ctx = ri.get_reply_service_context(
                    SFSBVersionConstants.SFSB_VERSION_SERVICE_CONTEXT_ID);
            if (ctx != null) {
                long version = Utility.bytesToLong(ctx.context_data, 0);
                SFSBClientVersionManager.setClientVersion(oidInfo.getContainerId(),
                    oidInfo.getInstanceKey(), version);
                if (_logger.isLoggable(Level.FINE)) {
                    _logger.log(Level.FINE, "**SFSBClientInterceptor." + callName
                            + " " + ri.operation() + " " + oidInfo
                            + " version: " + version);
                }
            }
        }
    }

    public void receive_reply(ClientRequestInfo ri) {
        receiveSFSBVersionNumber("receive_reply", ri);
    }
    
    public void receive_exception(ClientRequestInfo ri) throws ForwardRequest {
        receiveSFSBVersionNumber("receive_exception", ri);
    }

    public void receive_other(ClientRequestInfo ri) throws ForwardRequest {
        if (doesSFSBVersionPolicyExist(ri)) {
            EJBTargetKeyInfo oidInfo = new EJBTargetKeyInfo(ri
                    .effective_target());
            if (_logger.isLoggable(Level.WARNING)) {
                _logger.log(Level.WARNING, "**SFSBClientInterceptor.receive_other...: "
                    + oidInfo);
            }
        }
    }

    public boolean doesSFSBVersionPolicyExist(ClientRequestInfo ri) {
        boolean result = false;
        try {
            TaggedComponent sfsbVersionTag = ri
                    .get_effective_component(POARemoteReferenceFactory.SFSB_VERSION_POLICY_TYPE);
            result = (sfsbVersionTag != null);
        } catch (BAD_PARAM e) {
            // ignore
        }
        return result;
    }
    
}
