package org.maachang.comet.net ;

import java.util.ArrayList;
import java.util.List;

import org.maachang.comet.httpd.HttpSocket;

/**
 * コネクション中ソケット管理.
 * 
 * @version 2007/11/17
 * @author  masahito suzuki
 * @since   MaachangComet 1.00
 */
public class HttpSocketManager {
    
    private List<HttpSocket> manager = null ;
    
    public HttpSocketManager() {
        this.manager = new ArrayList<HttpSocket>() ;
    }
    
    protected void finalize() throws Exception {
        this.destroy() ;
    }
    
    public synchronized void destroy() {
        if( this.manager != null ) {
            int len = this.manager.size() ;
            for( int i = 0 ; i < len ; i ++ ) {
                HttpSocket v = this.manager.get( i ) ;
                if( v != null ) {
                    v.destroy() ;
                }
            }
            this.manager = null ;
        }
    }
    
    public synchronized void append( HttpSocket v ) {
        if( isClosed() == true || v == null || v.isClosed() == true ) {
            return ;
        }
        this.manager.add( v ) ;
    }
    
    public synchronized HttpSocket get( int no ) {
        if( isClosed() == true || no < 0 || no >= this.manager.size() ) {
            return null ;
        }
        return this.manager.get( no ) ;
    }
    
    public synchronized void remove( int no ) {
        if( isClosed() == true || no < 0 || no >= this.manager.size() ) {
            return ;
        }
        this.manager.remove( no ) ;
    }
    
    public synchronized int size() {
        if( isClosed() == true ) {
            return 0 ;
        }
        return this.manager.size() ;
    }
    
    public synchronized boolean isClosed() {
        if( this.manager == null ) {
            return true ;
        }
        return false ;
    }
}
