/** 
 * 
 * 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 org.activeio.AsynchChannel;
import org.activeio.AsynchChannelListener;
import org.activeio.Packet;
import org.activeio.SynchChannel;

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

/**
 * Adapts a {@see org.activeio.AsynchChannel} so that it provides an 
 * {@see org.activeio.SynchChannel} interface.  
 * 
 * This object buffers asynchronous messages from the {@see org.activeio.AsynchChannel} 
 * and buffers them in a {@see EDU.oswego.cs.dl.util.concurrent.Channel} util the client receives them.
 * 
 * @version $Revision$
 */
final public class AsynchToSynchChannelAdapter implements SynchChannel, AsynchChannelListener {

    private final AsynchChannel asynchChannel;    
    private final Channel buffer;

    static public SynchChannel adapt(org.activeio.Channel channel) {
        return adapt(channel, new LinkedQueue());
    }

    static public SynchChannel adapt(org.activeio.Channel channel, Channel upPacketChannel) {

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

        // Can we just just undo the adaptor
        if( channel.getClass() == SynchToAsynchChannelAdapter.class ) {
            return ((SynchToAsynchChannelAdapter)channel).getSynchChannel();
        }
        
        return new AsynchToSynchChannelAdapter((AsynchChannel)channel, upPacketChannel);        
    }
    
    /**
     * @deprecated {@see #adapt(AsynchChannel)}
     */
    public AsynchToSynchChannelAdapter(AsynchChannel asynchChannel) {
        this(asynchChannel, new LinkedQueue());
    }
    
    /**
     * @deprecated {@see #adapt(AsynchChannel, Channel)}
     */
    public AsynchToSynchChannelAdapter(AsynchChannel asynchChannel, Channel upPacketChannel){
        this.asynchChannel = asynchChannel;
        this.asynchChannel.setAsynchChannelListener(this);
        this.buffer=upPacketChannel;
    }

    /**
     * @see org.activeio.Channel#write(org.activeio.channel.Packet)
     */
    public void write(org.activeio.Packet packet) throws IOException {
        asynchChannel.write(packet);
    }

    /**
     * @see org.activeio.Channel#flush()
     */
    public void flush() throws IOException {
        asynchChannel.flush();
    }

    /**
     * @see org.activeio.SynchChannel#read(long)
     */
    public Packet read(long timeout) throws IOException {
        try {
            
            Object o;
            if( timeout == NO_WAIT_TIMEOUT ) {
                o = buffer.poll(0);
            } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
                o = buffer.take();            
            } else {
                o = buffer.poll(timeout);                        
            }
            
            if( o == null )
                return null;
            
            if( o instanceof Packet )
                return (Packet)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() {
        asynchChannel.dispose();
    }

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

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

    /**
     * @see org.activeio.AsynchChannelListener#onPacket(org.activeio.channel.Packet)
     */
    public void onPacket(Packet packet) {
        try {
            buffer.put(packet);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }        
    }

    /**
     * @see org.activeio.AsynchChannelListener#onPacketError(org.activeio.channel.ChannelException)
     */
    public void onPacketError(IOException error) {
        try {
            buffer.put(error);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }        
    }

    public Object narrow(Class target) {
        if( target.isAssignableFrom(getClass()) ) {
            return this;
        }
        return asynchChannel.narrow(target);
    }    

    public AsynchChannel getAsynchChannel() {
        return asynchChannel;
    }
    
    public String toString() {
        return asynchChannel.toString();
    }
}