package org.maachang.dbm.service.client ;

import java.util.ArrayList;
import java.util.Enumeration;

/**
 * MDbmConnection次情報管理用.
 * 
 * @version 2008/01/20
 * @author masahito suzuki
 * @since MaachangDBM 1.03
 */
class MDbmEnumConnection implements Enumeration<byte[]> {
    
    private MDbmClientConnection conn = null ;
    private ArrayList<byte[]> keys = null ;
    private int offset = 0 ;
    private boolean first = false ;
    
    private MDbmEnumConnection() {
        
    }
    
    public MDbmEnumConnection( MDbmClientConnection conn )
        throws Exception {
        if( conn == null || conn.isUse() == false ) {
            throw new IllegalArgumentException( "コネクション接続が確立していません" ) ;
        }
        conn.initKey() ;
        this.conn = conn ;
    }
    
    protected void finalize() throws Exception {
        conn = null ;
    }
    
    public boolean hasMoreElements() {
        return ( getKey( true ) == null ) ? false : true ;
    }
    
    public byte[] nextElement() {
        return getKey( false ) ;
    }
    
    private byte[] getKey( boolean mode ) {
        if( conn == null || conn.isUse() == false ) {
            return null ;
        }
        byte[] ret = null ;
        if( first == false ) {
            first = true ;
            try {
                keys = conn.getKey() ;
                offset = 0 ;
            } catch( Exception e ) {
                keys = null ;
            }
        }
        else {
            if( keys == null || keys.size() == 0 ) {
                keys = null ;
                return null ;
            }
            if( keys.size() <= offset ) {
                keys = null ;
                try {
                    keys = conn.getKey() ;
                    offset = 0 ;
                } catch( Exception e ) {
                    keys = null ;
                }
            }
        }
        if( keys == null || keys.size() == 0 ) {
            keys = null ;
        }
        else {
            ret = keys.get( offset ) ;
            if( mode == false ) {
                offset ++ ;
            }
        }
        return ret ;
    }
}
