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

import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
import EDU.oswego.cs.dl.util.concurrent.BoundedChannel;
import EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue;
import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.io.WireFormat;
import org.codehaus.activemq.io.WireFormatLoader;
import org.codehaus.activemq.message.Packet;
import org.codehaus.activemq.message.WireFormatInfo;
import org.codehaus.activemq.transport.TransportChannelSupport;
import org.codehaus.activemq.transport.TransportStatusEvent;
import org.codehaus.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.UnknownHostException;

/**
 * A tcp implementation of a TransportChannel
 *
 * @version $Revision: 1.3 $
 */
public class TcpTransportChannel extends TransportChannelSupport implements Runnable {
    private static final int SOCKET_BUFFER_SIZE = 64 * 1024;
    private static final Log log = LogFactory.getLog(TcpTransportChannel.class);
    protected Socket socket;
    private WireFormatLoader wireFormatLoader;
    private WireFormat currentWireFormat;
    private DataOutputStream dataOut;
    private DataInputStream dataIn;
    private SynchronizedBoolean closed;
    private SynchronizedBoolean started;
    private Object outboundLock;
    private Executor executor;
    private Thread thread;
    private boolean useAsyncSend = false;
    private boolean changeTimeout = false;
    private int soTimeout = 5000;
    private BoundedChannel exceptionsList;

    /**
     * Construct basic helpers
     * @param wireFormat
     */
    protected TcpTransportChannel(WireFormat wireFormat) {
        this.wireFormatLoader = new WireFormatLoader(wireFormat);
        closed = new SynchronizedBoolean(false);
        started = new SynchronizedBoolean(false);
        // there's not much point logging all exceptions, lets just keep a few around
        exceptionsList = new BoundedLinkedQueue(10);
        outboundLock = new Object();
        if (useAsyncSend) {
            executor = new PooledExecutor(new BoundedBuffer(1000), 1);
        }
    }

    /**
     * Connect to a remote Node - e.g. a Broker
     * @param wireFormat
     *
     * @param remoteLocation
     * @throws JMSException
     */
    public TcpTransportChannel(WireFormat wireFormat, URI remoteLocation) throws JMSException {
        this(wireFormat);
        try {
            this.socket = createSocket(remoteLocation);
            initialiseSocket();
        }
        catch (Exception ioe) {
            throw JMSExceptionHelper.newJMSException("Initialization of TcpTransportChannel failed. " +
                    "URI was: " + remoteLocation + " Reason: " + ioe, ioe);
        }
    }

    /**
     * Connect to a remote Node - e.g. a Broker
     * @param wireFormat
     * @param remoteLocation
     * @param localLocation  - e.g. local InetAddress and local port
     * @throws JMSException
     */
    public TcpTransportChannel(WireFormat wireFormat, URI remoteLocation, URI localLocation) throws JMSException {
        this(wireFormat);
        try {
            this.socket = createSocket(remoteLocation, localLocation);
            initialiseSocket();
        }
        catch (Exception ioe) {
            throw JMSExceptionHelper.newJMSException("Initialization of TcpTransportChannel failed: " + ioe, ioe);
        }
    }

    /**
     * @param wireFormat
     * @param socket
     * @param executor
     * @throws JMSException
     */
    public TcpTransportChannel(WireFormat wireFormat, Socket socket, Executor executor) throws JMSException {
        this(wireFormat);
        this.socket = socket;
        this.executor = executor;
        setServerSide(true);
        try {
            initialiseSocket();
        }
        catch (IOException ioe) {
            throw JMSExceptionHelper.newJMSException("Initialization of TcpTransportChannel failed: " + ioe, ioe);
        }
    }

    /**
     * start listeneing for events
     *
     * @throws JMSException if an error occurs
     */
    public void start() throws JMSException {
        if (started.commit(false, true)) {
            thread = new Thread(this, toString());
            if (isServerSide()) {
                thread.setDaemon(true);
            }
            else {
                thread.setPriority(Thread.NORM_PRIORITY + 2);
            }
            thread.start();
            //send the wire format
            if (isServerSide()) {
                WireFormatInfo info = new WireFormatInfo();
                info.setVersion(getCurrentWireFormatVersion());
                asyncSend(info);
            }else {
                try {
                getWireFormat().initiateProtocol(dataOut);
                dataOut.flush();
                }catch(IOException ioe){
                    String errorStr = "Failed to initiateProtocol";
                    log.error(errorStr,ioe);
                    JMSException jmsEx = new JMSException(errorStr);
                    jmsEx.setLinkedException(ioe);
                    throw jmsEx;
                }
            }
        }
    }

    /**
     * close the channel
     */
    public void stop() {
        if (closed.commit(false, true)) {
            super.stop();
            try {
                stopExecutor(executor);
                dataOut.close();
                dataIn.close();
                socket.close();
            }
            catch (Exception e) {
                log.warn("Caught while closing: " + e + ". Now Closed", e);
            }
        }
        closed.set(true);
    }

    
	public void forceDisconnect() {
		log.debug("Forcing disconnect");
		if (socket != null && socket.isConnected()) {
			try {
				socket.close();
			} catch (IOException e) {
				// Ignore
			}
		}
	}
    
    /**
     * Asynchronously send a Packet
     *
     * @param packet
     * @throws JMSException
     */
    public void asyncSend(final Packet packet) throws JMSException {
        if (executor != null) {
            try {
                executor.execute(new Runnable() {
                    public void run() {
                        try {
                            if (!closed.get()) {
                                doAsyncSend(packet);
                            }
                        }
                        catch (JMSException e) {
                            try {
                                exceptionsList.put(e);
                            }
                            catch (InterruptedException e1) {
                                log.warn("Failed to add element to exception list: " + e1);
                            }
                        }
                    }
                });
            }
            catch (InterruptedException e) {
                log.info("Caught: " + e, e);
            }
            try {
                JMSException e = (JMSException) exceptionsList.poll(0);
                if (e != null) {
                    throw e;
                }
            }
            catch (InterruptedException e1) {
                log.warn("Failed to remove element to exception list: " + e1);
            }
        }
        else {
            doAsyncSend(packet);
        }
    }

    /**
     * @return false
     */
    public boolean isMulticast() {
        return false;
    }

    /**
     * reads packets from a Socket
     */
    public void run() {
        log.trace("TCP consumer thread starting");
        int count = 0;
        boolean determinedWireFormat = false;
        while (!closed.get()) {
            if (isServerSide() && ++count > 500) {
                count = 0;
                Thread.yield();
            }
            int type = 0;
            try {
                if (changeTimeout) {
                    socket.setSoTimeout(soTimeout);
                }
                while ((type = dataIn.read()) == 0) {
                }
                if (type == -1) {
                    log.info("The socket peer is now closed");
                    doClose(new JMSException("Socket peer is now closed"));
                    stop();
                }
                else {
                    if (changeTimeout) {
                        socket.setSoTimeout(0);
                    }
                    if (!determinedWireFormat){
                        determinedWireFormat = true;
                        currentWireFormat = wireFormatLoader.getWireFormat(type);
                    }
                    Packet packet = getWireFormat().readPacket(type, dataIn);
                    if (packet != null) {
                        doConsumePacket(packet);
                    }
                }
            }
            catch (SocketTimeoutException e) {
                //onAsyncException(JMSExceptionHelper.newJMSException(e));
            }
            catch (InterruptedIOException e) {
                // TODO confirm that this really is a bug in the AS/400 JVM
                // Patch for AS/400 JVM
                // lets ignore these exceptions
                // as they typically just indicate the thread was interupted
                // while waiting for input, not that the socket is in error
                //onAsyncException(JMSExceptionHelper.newJMSException(e));
            }
            catch(JMSException jmsEx){
                log.warn("Failed to determine the wire format",jmsEx);
                doClose(jmsEx);
            }
            catch (IOException e) {
                doClose(e);
            }
        }
    }

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

    /**
     * @return the socket used by the TcpTransportChannel
     */
    public Socket getSocket() {
        return socket;
    }

    /**
     * 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 getWireFormat().canProcessWireFormatVersion(version);
    }

    /**
     * @return the current version of this wire format
     */
    public int getCurrentWireFormatVersion() {
        return getWireFormat().getCurrentWireFormatVersion();
    }

    // Properties
    //-------------------------------------------------------------------------
    /**
     * @return true if the so timeout is changed when receiving packets
     */
    public boolean isChangeTimeout() {
        return changeTimeout;
    }

    /**
     * Set the changeTimeout flag - if set the timeout value is changed after receiving a packet
     * When receiving a packet, so timeout is set to zero (inifinite) after receiving the first byte, which determines
     * the packet type. resetting the value is an overhead, but on some operating systems (Solaris), detecting that
     * a socket peer has disconnected is only possible with so timeout set to a non-zero value
     * @param changeTimeout
     */
    public void setChangeTimeout(boolean changeTimeout) {
        this.changeTimeout = changeTimeout;
    }

    /**
     * @return true if packets are enqueued to a separate queue before dispatching
     */
    public boolean isUseAsyncSend() {
        return useAsyncSend;
    }

    /**
     * set the useAsync flag
     * @param useAsyncSend
     */
    public void setUseAsyncSend(boolean useAsyncSend) {
        this.useAsyncSend = useAsyncSend;
    }

    /**
     * @return the current so timeout used on the socket
     */
    public int getSoTimeout() {
        return soTimeout;
    }

    /**
     * set the socket so timeout
     * @param soTimeout
     */
    public void setSoTimeout(int soTimeout) {
        this.soTimeout = soTimeout;
        this.changeTimeout = true;
    }

    // Implementation methods
    //-------------------------------------------------------------------------
    /**
     * Actually performs the async send of a packet
     *
     * @param packet
     * @throws JMSException
     */
    protected void doAsyncSend(Packet packet) throws JMSException {
        try {
            synchronized (outboundLock) {
                getWireFormat().writePacket(packet, dataOut);
                dataOut.flush();
            }
        }
        catch (IOException e) {
            if (closed.get()) {
                log.trace("Caught exception while closed: " + e, e);
            }
            else {
                throw JMSExceptionHelper.newJMSException("asyncSend failed: " + e, e);
            }
        }
        catch (JMSException e) {
            if (closed.get()) {
                log.trace("Caught exception while closed: " + e, e);
            }
            else {
                throw e;
            }
        }
    }

    private void doClose(Exception ex) {
        if (!closed.get()) {
        	fireStatusEvent(new TransportStatusEvent(TransportStatusEvent.DISCONNECTED));
            setPendingStop(true);
            onAsyncException(JMSExceptionHelper.newJMSException("Error reading socket: " + ex, ex));
            stop();
        }
    }

    /**
     * Configures the socket for use
     *
     * @throws IOException
     */
    protected void initialiseSocket() throws IOException {
        socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
        socket.setSendBufferSize(SOCKET_BUFFER_SIZE);
        socket.setSoTimeout(soTimeout);
        BufferedInputStream buffIn = new BufferedInputStream(socket.getInputStream());
        this.dataIn = new DataInputStream(buffIn);
        TcpBufferedOutputStream buffOut = new TcpBufferedOutputStream(socket.getOutputStream());
        this.dataOut = new DataOutputStream(buffOut);
    	fireStatusEvent(new TransportStatusEvent(TransportStatusEvent.CONNECTED));
    }

    /**
     * Factory method to create a new socket
     *
     * @param remoteLocation the URI to connect to
     * @return the newly created socket
     * @throws UnknownHostException
     * @throws IOException
     */
    protected Socket createSocket(URI remoteLocation) throws UnknownHostException, IOException {
        return new Socket(remoteLocation.getHost(), remoteLocation.getPort());
    }

    /**
     * Factory method to create a new socket
     *
     * @param remoteLocation
     * @param localLocation
     * @return @throws IOException
     * @throws IOException
     * @throws UnknownHostException
     */
    protected Socket createSocket(URI remoteLocation, URI localLocation) throws IOException, UnknownHostException {
        return new Socket(remoteLocation.getHost(), remoteLocation.getPort(), InetAddress.getByName(localLocation
                .getHost()), localLocation.getPort());
    }
    
    private WireFormat getWireFormat(){
        if (currentWireFormat != null){
            return currentWireFormat;
        }
        return wireFormatLoader.getPreferedWireFormat();
    }
}