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

import org.activeio.AsynchChannel;
import org.activeio.AsynchChannelFactory;
import org.activeio.AsynchChannelServer;
import org.activeio.ChannelFactory;
import org.activeio.SynchChannelFactory;

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

/**
 * @version $Revision$
 */
public class SynchToAsynchChannelFactoryAdaptor implements AsynchChannelFactory {
    
    private final SynchChannelFactory synchChannelFactory;
    private final Executor executor;
        
    static public AsynchChannelFactory adapt(SynchChannelFactory channelFactory) {
        return adapt(channelFactory, ChannelFactory.DEFAULT_EXECUTOR);
    }
    
    static public AsynchChannelFactory adapt(SynchChannelFactory channelFactory, Executor executor ) {

        // It might not need adapting
        if( channelFactory instanceof AsynchChannelFactory ) {
            return (AsynchChannelFactory) channelFactory;
        }

        // Can we just just undo the adaptor
        if( channelFactory.getClass() == AsynchToSynchChannelFactoryAdaptor.class ) {
            return ((AsynchToSynchChannelFactoryAdaptor)channelFactory).getAsynchChannelFactory();
        }
        
        return new SynchToAsynchChannelFactoryAdaptor((SynchChannelFactory)channelFactory, executor);        
    }
    
    /**
     * @deprecated {@see #adapt(SynchChannelFactory)}
     */
    public SynchToAsynchChannelFactoryAdaptor(final SynchChannelFactory next) {
        this(next, ChannelFactory.DEFAULT_EXECUTOR);
    }
    
    /**
     * @deprecated {@see #adapt(SynchChannelFactory, Executor)}
     */
    public SynchToAsynchChannelFactoryAdaptor(final SynchChannelFactory next, Executor executor) {
        this.synchChannelFactory = next;
        this.executor = executor;
    }
        
    public AsynchChannel openAsynchChannel(URI location) throws IOException {
        return SynchToAsynchChannelAdapter.adapt(synchChannelFactory.openSynchChannel(location),executor);
    }

    public AsynchChannelServer bindAsynchChannel(URI location) throws IOException {
        return new SynchToAsynchChannelServerAdapter(synchChannelFactory.bindSynchChannel(location),executor);
    }
    
    public SynchChannelFactory getSynchChannelFactory() {
        return synchChannelFactory;
    }
}
