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

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

import org.activeio.SynchChannel;
import org.activeio.SynchChannelFactory;
import org.activeio.SynchChannelServer;

/**
 * A TcpSynchChannelFactory creates {@see org.activeio.net.TcpSynchChannel}
 * and {@see org.activeio.net.TcpSynchChannelServer} objects.
 * 
 * @version $Revision$
 */
public class SocketSynchChannelFactory implements SynchChannelFactory {

    protected static final int DEFAULT_BACKLOG = 500;

    private final SocketFactory socketFactory;
    private final ServerSocketFactory serverSocketFactory;
    private int backlog = DEFAULT_BACKLOG;
    
    public SocketSynchChannelFactory() {
        this(SocketFactory.getDefault(), ServerSocketFactory.getDefault());
    }

    public SocketSynchChannelFactory(SocketFactory socketFactory, ServerSocketFactory serverSocketFactory) {
        this.socketFactory = socketFactory;
        this.serverSocketFactory = serverSocketFactory;
    }
        
    /**
     * Uses the {@param location}'s host and port to create a tcp connection to a remote host.
     * 
     * @see org.activeio.SynchChannelFactory#openSynchChannel(java.net.URI)
     */
    public SynchChannel openSynchChannel(URI location) throws IOException {
        Socket socket=null;
        socket = socketFactory.createSocket(location.getHost(), location.getPort());
        return createSynchChannel(socket);
    }

    /**
     * @param socket
     * @return
     * @throws IOException
     */
    protected SynchChannel createSynchChannel(Socket socket) throws IOException {
        return new SocketSynchChannel(socket);
    }

    /**
     * Binds a server socket a the {@param location}'s port. 
     * 
     * @see org.activeio.SynchChannelFactory#bindSynchChannel(java.net.URI)
     */
    public SynchChannelServer bindSynchChannel(URI bindURI) throws IOException {
        
        String host = bindURI.getHost();
        InetAddress addr;
        if( (host == null || host.length() == 0 || host.equals("localhost") ) ) {            
            addr = InetAddress.getLocalHost();
        } else {
            addr = InetAddress.getByName(host);            
        }
        ServerSocket serverSocket;
        
        if (addr.equals(InetAddress.getLocalHost())) {
            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog);
        } else {
            serverSocket = serverSocketFactory.createServerSocket(bindURI.getPort(), backlog, addr);
        }

        URI connectURI=bindURI;
        try {
            connectURI = URISupport.changeHost(connectURI, addr.getHostName());
            connectURI = URISupport.changePort(connectURI, serverSocket.getLocalPort());
        } catch (URISyntaxException e) {
            throw (IOException)new IOException("Could build connect URI: "+e).initCause(e);
        }
        
        return new SocketSynchChannelServer(serverSocket, bindURI, connectURI);
    }
    
    /**
     * @return Returns the backlog.
     */
    public int getBacklog() {
        return backlog;
    }

    /**
     * @param backlog
     *            The backlog to set.
     */
    public void setBacklog(int backlog) {
        this.backlog = backlog;
    }


}
