package com.eactive.eai.adapter.socket.service; 

import java.util.Iterator;
import java.util.Vector;

import com.eactive.eai.adapter.socket.config.SocketAdapterManager;

public class OutboundChannel 
{ 
    private     Vector<SocketService> connectionList;      
    
    public OutboundChannel(long sessionTimeout) {
        connectionList = new Vector<SocketService>();
    }
    
    public  void addConnection( SocketService connection ) throws Exception {
        synchronized ( this.connectionList ) {
            SocketService svc = connection;
            if ( svc.getContext().isStarted() && svc.isActive() ) {
                if ( connectionList.size() == 0 ) {
                    SocketAdapterManager.getInstance().changeAdapterStatus( connection, true );
                }
                this.connectionList.add( connection );
            } 
        }
    }
    
    public int getPoolSize() {
        return connectionList.size();
    }
    
    public  Object getConnection() throws Exception {
        synchronized ( this.connectionList ) {
            if ( this.connectionList.size() > 0 ) {
                try {
                    SocketService svc = (SocketService) connectionList.remove( 0 );
                    if ( svc.getContext().isStarted() && svc.isActive() ) {
                        return svc;
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public  void removeConnection( Object connection ) throws Exception {
        synchronized ( this.connectionList ) {
            int size = this.connectionList.size();
            for( int i=0; i < size; i++ ) {
                Object x = this.connectionList.elementAt( i );
                if ( x == connection ) {
                    this.connectionList.remove( i );
                    break;
                }
            }
        }
    }
    
    public void removeAllConnection() throws Exception {
        this.connectionList.clear();
    }
    
    public String toString() {
        StringBuffer sb = new StringBuffer();
        
        for(Iterator<SocketService> iter = connectionList.iterator(); iter.hasNext();) {
            Object key = iter.next();
            sb.append("\n    ▣ " + key);
        }

        return sb.toString();
    }
} 
