/**
 * 
 * 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.transport.vm;

import EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue;
import EDU.oswego.cs.dl.util.concurrent.Channel;
import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.broker.BrokerConnector;
import org.codehaus.activemq.message.Packet;
import org.codehaus.activemq.message.PacketListener;
import org.codehaus.activemq.transport.TransportChannelListener;
import org.codehaus.activemq.transport.TransportChannelSupport;

import javax.jms.JMSException;

/**
 * A VM implementation of a TransportChannel
 *
 * @version $Revision: 1.2 $
 */
public class VmTransportChannel extends TransportChannelSupport implements Runnable {

    private static final Log log = LogFactory.getLog(VmTransportChannel.class);
    private static final Object TERMINATE = new Object();
    private static int lastThreadId = 0; // To number the threads.

    // properties
    private Channel sendChannel;
    private Channel receiveChannel;
    private int sendCapacity = 10;
    private int receiveCapacity = 10;
    private boolean asyncSend = false;

    // state
    private SynchronizedBoolean closed;
    private SynchronizedBoolean started;
    private Thread thread; //need to change this - and use a thread pool
    private PacketListener sendListener;
    private VmTransportChannel clientSide;

    public VmTransportChannel() {
        closed = new SynchronizedBoolean(false);
        started = new SynchronizedBoolean(false);
    }

    public VmTransportChannel(Channel sendChannel, Channel receiveChannel) {
        this();
        this.sendChannel = sendChannel;
        this.receiveChannel = receiveChannel;
    }

    public VmTransportChannel(int capacity) {
        this(new BoundedLinkedQueue(capacity), new BoundedLinkedQueue(capacity));
    }

    public void start() throws JMSException {
        if (started.commit(false, true)) {
            if (isAsyncSend()) {
                // lets force the lazy construction
                // as we sometimes need to create these early when
                // wiring together with a server side channel
                getSendChannel();
                getReceiveChannel();

                thread = new Thread(this, "VM Transport: " + getNextThreadId());
                if (isServerSide()) {
                    thread.setDaemon(true);
                }
                thread.start();
            }
        }
    }

    public void stop() {
        if (closed.commit(false, true)) {
            super.stop();
            try {
                // to close the channel, lets send a null
                if (sendChannel != null) {
                    sendChannel.put(TERMINATE);
                }
                if (receiveChannel != null) {
                    receiveChannel.put(TERMINATE);
                }

                if (thread != null) {
                    // lets wait for the receive thread to terminate
                    thread.join();
                }
            }
            catch (Exception e) {
                log.trace(toString() + " now closed with exception: " + e);
            }
        }
    }
    
	public void forceDisconnect() {
		throw new IllegalStateException("Disconnection not applicable for VM transport");
	}
    
    /**
     * Asynchronously send a Packet
     *
     * @param packet
     * @throws JMSException
     */
    public void asyncSend(Packet packet) throws JMSException {
        if (sendChannel != null) {
            while (true) {
                try {
                    sendChannel.put(packet);
                    break;
                }
                catch (InterruptedException e) {
                    // continue
                }
            }
        }
        else {
            if (sendListener == null) {
                if (clientSide != null) {
                    sendListener = clientSide.createPacketListenerSender();
                }
            }
            if (sendListener != null) {
                sendListener.consume(packet);
            }
            else {
                throw new JMSException("No sendListener available");
            }
        }
    }


    public boolean isMulticast() {
        return false;
    }

    /**
     * reads packets from a Socket
     */
    public void run() {
        while (!closed.get()) {
            try {
                Object answer = receiveChannel.take();
                if (answer == TERMINATE) {
                    log.trace("The socket peer is now closed");
                    stop();
                    return;
                }
                else if (answer != null) {
                    Packet packet = (Packet) answer;
                    // we might have just got a packet in but we've already shut down
                    if (closed.get()) {
                        break;
                    }
                    doConsumePacket(packet);
                }
            }
            catch (InterruptedException e) {
                // continue
            }
        }
    }

    /**
     * pretty print for object
     *
     * @return String representation of this object
     */
    public String toString() {
        return "VmTransportChannel: " + sendChannel;
    }

    /**
     * Connects the client side transport channel with the broker
     */
    public void connect(BrokerConnector brokerConnector) throws JMSException {
        TransportChannelListener listener = (TransportChannelListener) brokerConnector;
        VmTransportChannel serverSide = createServerSide();
        listener.addClient(serverSide);
        serverSide.start();
    }

    /**
     * Creates the server side version of this client side channel. On the server side
     * the client's side sendChannel is the receiveChannel and vice versa
     *
     * @return
     */
    public VmTransportChannel createServerSide() throws JMSException {
        VmTransportChannel channel = new VmTransportChannel(getReceiveChannel(), getSendChannel());
        channel.clientSide = this;
        return channel;
    }

    public void setPacketListener(PacketListener listener) {
        super.setPacketListener(listener);
        if (clientSide != null) {
            clientSide.sendListener = listener;

        }
    }
    
    /**
     * Can this wireformat process packets of this version
     * @param version the version number to test
     * @return true if can accept the version
     */
    public boolean canProcessWireFormatVersion(int version){
        return true;
    }
    
    /**
     * @return the current version of this wire format
     */
    public int getCurrentWireFormatVersion(){
        return 1;
    }

    // Properties
    //-------------------------------------------------------------------------
    public int getReceiveCapacity() {
        return receiveCapacity;
    }

    public void setReceiveCapacity(int receiveCapacity) {
        this.receiveCapacity = receiveCapacity;
    }

    public int getSendCapacity() {
        return sendCapacity;
    }

    public void setSendCapacity(int sendCapacity) {
        this.sendCapacity = sendCapacity;
    }

    public boolean isAsyncSend() {
        return asyncSend;
    }

    public void setAsyncSend(boolean asyncSend) {
        this.asyncSend = asyncSend;
    }

    public Channel getSendChannel() {
        if (isAsyncSend()) {
            if (sendChannel == null) {
                sendChannel = createChannel(getSendCapacity());
            }
        }
        return sendChannel;
    }

    public void setSendChannel(Channel sendChannel) {
        this.sendChannel = sendChannel;
    }

    public Channel getReceiveChannel() {
        if (isAsyncSend()) {
            if (receiveChannel == null) {
                receiveChannel = createChannel(getReceiveCapacity());
            }
        }
        return receiveChannel;
    }

    public void setReceiveChannel(Channel receiveChannel) {
        this.receiveChannel = receiveChannel;
    }

    // Implementation methods
    //-------------------------------------------------------------------------
    protected static synchronized int getNextThreadId() {
        return lastThreadId++;
    }

    protected Channel createChannel(int capacity) {
        return new BoundedLinkedQueue(capacity);
    }

    /**
     * Creates a sender PacketListener which handles any receipts then delegates
     * to the ultimate PacketListener (typically the JMS client)
     *
     * @return
     */
    protected PacketListener createPacketListenerSender() {
        return new PacketListener() {
            public void consume(Packet packet) {
                doConsumePacket(packet, getPacketListener());
            }
        };
    }

    protected void doClose(Exception ex) {
        if (!closed.get()) {
            JMSException jmsEx = new JMSException("Error reading socket: " + ex.getMessage());
            jmsEx.setLinkedException(ex);
            onAsyncException(jmsEx);
            stop();
        }
    }
}