package org.maachang.dbm.engine ;

import java.util.Enumeration;
import java.util.NoSuchElementException;

/**
 * 次情報管理用.
 * 
 * @version 2008/06/05
 * @author masahito suzuki
 * @since MaachangDBM 1.12
 */
class M2Enumeration implements Enumeration<byte[]> {
    
    /**
     * DBM-Engine.
     */
    private M2Engine engine = null ;
    
    /**
     * キー管理用.
     */
    private M2NextKey next = null ;
    
    /**
     * キー管理用.
     */
    private M2NextKey next2 = null ;
    
    /**
     * コンストラクタ.
     */
    private M2Enumeration() {
        
    }
    
    /**
     * コンストラクタ.
     * <BR><BR>
     * 条件を設定してオブジェクトを生成します.
     * <BR>
     * @param engine DBM-Engineを設定します.
     */
    protected M2Enumeration( M2Engine engine ) {
        this.engine = engine ;
    }
    
    protected void finalize() throws Exception {
        engine = null ;
        next = null ;
        next2 = null ;
    }
    
    /**
     * Tests if this enumeration contains more elements.
     *
     * @return  <code>true</code> if and only if this enumeration object
     *           contains at least one more element to provide;
     *          <code>false</code> otherwise.
     */
    public boolean hasMoreElements() {
        if( next2 == null ) {
            try {
                next2 = this.engine.next( next ) ;
            } catch( Exception e ) {
                next2 = null ;
                return false ;
            }
        }
        if( next2 != null ) {
            return true ;
        }
        return false ;
    }
    
    /**
     * Returns the next element of this enumeration if this enumeration
     * object has at least one more element to provide.
     *
     * @return     the next element of this enumeration.
     * @exception  NoSuchElementException  if no more elements exist.
     */
    public byte[] nextElement() {
        byte[] ret = null ;
        if( next2 == null ) {
            try {
                next = this.engine.next( next ) ;
                if( next != null ) {
                    ret = next.getKey() ;
                }
            } catch( Exception e ) {
                ret = null ;
            }
            next2 = null ;
            return ret ;
        }
        else {
            next = next2 ;
            next2 = null ;
            if( next != null ) {
                ret = next.getKey() ;
            }
        }
        return ret ;
    }
}
