package org.maachang.comet.proxy ;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import org.maachang.comet.httpd.HttpSocket;
import org.maachang.comet.net.HttpServer;

/**
 * ProxyServerSocket.
 * 
 * @version 2007/11/17
 * @author  masahito suzuki
 * @since   MaachangComet 1.00
 */
class ProxyServerImpl implements HttpServer {
    
    private static final int TIMEOUT = 12000 ;
    private static final int DEFAULT_PORT = 3333 ;
    protected static final int MIN_LENGTH = 1 ;
    protected static final int MAX_LENGTH = 150 ;
    private ServerSocket serverSocket = null ;
    
    private ProxyServerImpl() { }
    
    public ProxyServerImpl( int port,int backlog )
        throws Exception {
        this( null,port,backlog ) ;
    }
    
    public ProxyServerImpl( InetAddress addr,int port,int backlog )
        throws Exception {
        if( backlog <= MIN_LENGTH ) {
            backlog = MIN_LENGTH ;
        }
        else if( backlog > MAX_LENGTH ) {
            backlog = MAX_LENGTH ;
        }
        if( port <= 0 || port > 65535 ) {
            port = DEFAULT_PORT ;
        }
        ServerSocket server = new ServerSocket() ;
        server.setReuseAddress( true ) ;
        server.setSoTimeout( TIMEOUT ) ;
        if( addr == null ) {
            server.bind( new InetSocketAddress( port ),backlog ) ;
        }
        else {
            server.bind( new InetSocketAddress( addr,port ),backlog ) ;
        }
        this.serverSocket = server ;
    }
    
    protected void finalize() throws Exception {
        this.destroy() ;
    }
    
    public void destroy() {
        if( this.serverSocket != null ) {
            try {
                this.serverSocket.close() ;
            } catch( Exception e ) {
            }
        }
        this.serverSocket = null ;
    }
    
    public HttpSocket accept() throws Exception {
        if( isClosed() == true ) {
            throw new IOException( "サーバソケットは利用出来ません" ) ;
        }
        HttpSocket ret = null ;
        try {
            Socket s = this.serverSocket.accept() ;
            ret = new ProxyHttpSocketImpl( s ) ;
        } catch( SocketTimeoutException st ) {
            ret = null ;
        } catch( Exception e ) {
            throw e ;
        }
        return ret ;
    }
    
    public ServerSocket serverSocket() {
        if( isClosed() == true ) {
            return null ;
        }
        return this.serverSocket ;
    }
    
    public boolean isClosed() {
        boolean ret = false ;
        try {
            if( this.serverSocket == null ||
                this.serverSocket.isBound() == false ||
                this.serverSocket.isClosed() == true ) {
                ret = true ;
            }
        } catch( Exception e ) {
            ret = true ;
        }
        return ret ;
    }
    
}
