/**
 * 
 * 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.activemq.transport.activeio;

import java.io.IOException;

import javax.jms.JMSException;

import org.activeio.AcceptListener;
import org.activeio.AsynchChannel;
import org.activeio.AsynchChannelServer;
import org.activeio.Channel;
import org.activeio.adapter.SynchToAsynchChannelAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.activemq.io.WireFormat;
import org.activemq.transport.TransportServerChannelSupport;
import org.activemq.util.JMSExceptionHelper;

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

/**
 * Binds to a well known port and listens for Sockets ...
 * 
 * @version $Revision: 1.1.1.1 $
 */
public class ActiveIOTransportServerChannel extends TransportServerChannelSupport implements AcceptListener {
    private static final Log log = LogFactory.getLog(ActiveIOTransportServerChannel.class);

    private final WireFormat wireFormat;

    private final AsynchChannelServer server;

    private final SynchronizedBoolean closed = new SynchronizedBoolean(false);

    /**
     * @param wireFormat
     * @param server
     */
    public ActiveIOTransportServerChannel(WireFormat wireFormat, AsynchChannelServer server) {
        super(server.getBindURI());
        this.wireFormat = wireFormat;
        this.server = server;
        server.setAcceptListener(this);
    }

    public void start() throws JMSException {
        try {
            super.start();
            server.start();
        } catch (IOException e) {
            throw JMSExceptionHelper.newJMSException(e.getMessage(), e);
        }
    }

    public void stop() throws JMSException {
        if (closed.commit(false, true)) {
            super.stop();
            server.dispose();
        }
    }

    /**
     * @return pretty print of this
     */
    public String toString() {
        return "ActiveIOTransportServerChannel@" + getUrl();
    }

    public void onAccept(Channel c) {
        if (closed.get()) {
            c.dispose();
            return;
        }

        AsynchChannel channel = SynchToAsynchChannelAdapter.adapt(c);
        // If the channel is not allready buffered.. lets buffer it.
        //if (channel.narrow(WriteBufferedAsynchChannel.class) == null
        //        && channel.narrow(WriteBufferedSynchChannel.class) == null) {
        //   channel = new WriteBufferedAsynchChannel(channel);
        //}
        addClient(new ActiveIOTransportChannel(wireFormat.copy(), channel));
    }

    public void onAcceptError(IOException error) {
        if (!closed.get()) {
            log.warn("Caught exception accepting connection: " + error, error);
            try {
                stop();
            } catch (JMSException e) {
            }
        }

    }

}