/**
 * 
 * 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.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.ChannelFactory;
import org.activeio.ChannelServer;
import org.activeio.Disposable;
import org.activeio.Service;
import org.activeio.SynchChannelServer;

import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.Latch;
import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;

/**
 * Adapts a {@see org.activeio,SynchChannelServer} so that it provides an 
 * {@see org.activeio.AsynchChannelServer} interface.  When this channel
 * is started, a background thread is used to poll the (@see org.activeio.SynchChannelServer}
 * for accepted channel connections which are then delivered to the {@see org.activeio.AcceptConsumer}.
 * 
 * @version $Revision$
 */
final public class SynchToAsynchChannelServerAdapter implements AsynchChannelServer, Runnable {

    private final SynchChannelServer synchChannelServer;
    private final SynchronizedBoolean running = new SynchronizedBoolean(false);
    private final Executor executor;
    private AcceptListener acceptListener;
    private Latch doneLatch;
    
    
    static public AsynchChannelServer adapt(ChannelServer channel) {
        return adapt(channel, ChannelFactory.DEFAULT_EXECUTOR);
    }

    static public AsynchChannelServer adapt(ChannelServer channel, Executor executor) {

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

        // Can we just just undo the adaptor
        if( channel.getClass() == SynchToAsynchChannelAdapter.class ) {
            return ((AsynchToSynchChannelServerAdapter)channel).getAsynchChannelServer();
        }
        
        return new SynchToAsynchChannelServerAdapter((SynchChannelServer)channel, executor);        
    }
    
    public SynchToAsynchChannelServerAdapter(SynchChannelServer synchServer) {
        this(synchServer, ChannelFactory.DEFAULT_EXECUTOR);
    }
    
    public SynchToAsynchChannelServerAdapter(SynchChannelServer synchServer, Executor executor) {
        this.synchChannelServer = synchServer;        
        this.executor=executor;
    }
    
    synchronized public void start() throws IOException {        
        if (running.commit(false, true)) {
            
            if( acceptListener == null )
                throw new IllegalStateException("AcceptListener must be set before object can be started.");

            synchChannelServer.start();
            
            try {
                doneLatch = new Latch();
                executor.execute(this);
            } catch (InterruptedException e) {
                throw new InterruptedIOException(e.getMessage());
            }
        }
    }

    synchronized public void stop(long timeout) throws IOException {
        if (running.commit(true, false)) {
            try {
                
                if( timeout == NO_WAIT_TIMEOUT ) {
                    synchChannelServer.stop(NO_WAIT_TIMEOUT);
                } else if( timeout == WAIT_FOREVER_TIMEOUT ) {
                    doneLatch.acquire();
                    synchChannelServer.stop(WAIT_FOREVER_TIMEOUT);
                } else {
                    
                    long start = System.currentTimeMillis();
                    if( doneLatch.attempt(timeout) ) {
                        timeout -= (System.currentTimeMillis() - start);
                    } else {
                        timeout=0;
                    }
                    
                    if( timeout <= 0 ) {
                        synchChannelServer.stop(NO_WAIT_TIMEOUT);
                    } else {
                        synchChannelServer.stop(timeout);
                    }
                }
                
            } catch (IOException e) {
                throw e;
            } catch (Throwable e) {
                throw (IOException)new IOException("stop failed: " + e.getMessage()).initCause(e);
            }
        }
    }

    public void run() {
        // Change the thread name.
        String oldName = Thread.currentThread().getName();        
        Thread.currentThread().setName( synchChannelServer.toString() );
        try {
	        while (running.get()) {
	            try {
	                Channel channel = synchChannelServer.accept(500);
	                if( channel == null )
	                    continue;                
	                acceptListener.onAccept(channel);
	            } catch (IOException e) {
	                if( running.get() )
	                    acceptListener.onAcceptError(e);        
	        	} catch (Throwable e) {        	    
	                if( running.get() )
	                    acceptListener.onAcceptError((IOException)new IOException("Unexpected Error: "+e).initCause(e));
	        	}
	        }
        } finally {
            if( doneLatch!=null )
                doneLatch.release();
            Thread.currentThread().setName(oldName);            
        }
    }

    /**
     * @see org.activeio.AsynchChannelServer#setAcceptListener(org.activeio.AcceptListener)
     */
    public void setAcceptListener(AcceptListener acceptListener) {
        if(running.get()) 
            throw new IllegalStateException("Cannot change the AcceptListener while the object is running.");        
        this.acceptListener = acceptListener;
    }

    /**
     * @see org.activeio.Disposable#dispose()
     */
    public void dispose() {
        try {
            stop(Service.NO_WAIT_TIMEOUT);
        } catch ( IOException ignore) {
        }
        if( synchChannelServer instanceof Disposable ) {
            ((Disposable)synchChannelServer).dispose();
        }
    }

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

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

    public SynchChannelServer getSynchChannelServer() {
        return synchChannelServer;
    }
    
    public Object narrow(Class target) {
        if( target.isAssignableFrom(getClass()) ) {
            return this;
        }
        return synchChannelServer.narrow(target);
    }    
    
    public String toString() {
        return synchChannelServer.toString();
    }
}