/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * 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.activeio.adapter;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;

import org.activeio.AcceptListener;
import org.activeio.AsynchChannelServer;
import org.activeio.Channel;
import org.activeio.ChannelServer;
import org.activeio.SynchChannelServer;

import EDU.oswego.cs.dl.util.concurrent.LinkedQueue;

/**
 * Adapts a {@see org.activeio.AsynchChannelServer} so that it provides an 
 * {@see org.activeio.SynchChannelServer} interface.  
 * 
 * This object buffers asynchronous accepts from the {@see org.activeio.AsynchChannelServer} 
 * abs buffers them in a {@see EDU.oswego.cs.dl.util.concurrent.Channel} util the client accepts the 
 * connection.
 * 
 * @version $Revision$
 */
final public class AsynchToSynchChannelServerAdapter implements SynchChannelServer, AcceptListener {

    private final AsynchChannelServer asynchChannelServer;    
    private final EDU.oswego.cs.dl.util.concurrent.Channel acceptBuffer;
    
    static public SynchChannelServer adapt(ChannelServer channel) {
        return adapt(channel, new LinkedQueue());
    }

    static public SynchChannelServer adapt(ChannelServer channel, EDU.oswego.cs.dl.util.concurrent.Channel upPacketChannel) {

        // It might not need adapting
        if( channel instanceof SynchChannelServer ) {
            return (SynchChannelServer) channel;
        }

        // Can we just just undo the adaptor
        if( channel.getClass() == SynchToAsynchChannelAdapter.class ) {
            return ((SynchToAsynchChannelServerAdapter)channel).getSynchChannelServer();
        }
        
        return new AsynchToSynchChannelServerAdapter((AsynchChannelServer)channel, upPacketChannel);        
    }
    
    /**
     * @deprecated {@see #adapt(ChannelServer)}
     */
    public AsynchToSynchChannelServerAdapter(AsynchChannelServer asynchChannelServer) {
        this(asynchChannelServer,new LinkedQueue());
    }
    
    /**
     * @deprecated {@see #adapt(ChannelServer, EDU.oswego.cs.dl.util.concurrent.Channel)}
     */
    public AsynchToSynchChannelServerAdapter(AsynchChannelServer asynchChannelServer, EDU.oswego.cs.dl.util.concurrent.Channel acceptBuffer) {
        this.asynchChannelServer = asynchChannelServer;
        this.acceptBuffer=acceptBuffer;
        this.asynchChannelServer.setAcceptListener(this);
    }

    /**
     * @see org.activeio.SynchChannelServer#accept(long)
     */
    public org.activeio.Channel accept(long timeout) throws IOException {
        try {
            
            Object o;
            if( timeout == NO_WAIT_TIMEOUT ) {
                o = acceptBuffer.poll(0);
            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
                o = acceptBuffer.take();            
            } else {
                o = acceptBuffer.poll(timeout);                        
            }
            
            if( o == null )
                return null;
            
            if( o instanceof Channel )
                return (Channel)o;
            
            Throwable e = (Throwable)o;
            throw (IOException)new IOException("Asynch error occured: "+e).initCause(e);
            
        } catch (InterruptedException e) {
            throw new InterruptedIOException(e.getMessage());
        }
    }
    /**
     * @see org.activeio.Disposable#dispose()
     */
    public void dispose() {
        asynchChannelServer.dispose();
    }

    /**
     * @see org.activeio.Service#start()
     */
    public void start() throws IOException {
        asynchChannelServer.start();
    }

    /**
     * @see org.activeio.Service#stop(long)
     */
    public void stop(long timeout) throws IOException {
        asynchChannelServer.stop(timeout);
    }

    public URI getBindURI() {
        return asynchChannelServer.getBindURI();
    }

    public URI getConnectURI() {
        return asynchChannelServer.getConnectURI();
    }

    /**
     * @see org.activeio.AcceptListener#onAccept(org.activeio.Channel)
     */
    public void onAccept(org.activeio.Channel channel) {
        try {
            acceptBuffer.put(channel);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }        
    }
    
    /**
     * @see org.activeio.AcceptListener#onAcceptError(java.io.IOException)
     */
    public void onAcceptError(IOException error) {
        try {
            acceptBuffer.put(error);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }        
    }
    
    public AsynchChannelServer getAsynchChannelServer() {
        return asynchChannelServer;
    }
    
    public Object narrow(Class target) {
        if( target.isAssignableFrom(getClass()) ) {
            return this;
        }
        return asynchChannelServer.narrow(target);
    }    
    
    public String toString() {
        return asynchChannelServer.toString();
    }
}