/**
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2004 satoshi akabane(akabane@logical-paradox.org)
 *
 */
package org.logical_paradox.fts;

import java.io.IOException;
import java.util.Enumeration;
import java.util.NoSuchElementException;

import jdbm.JDBMEnumeration;
import jdbm.JDBMHashtable;
import jdbm.JDBMRecordManager;

/**
 * @author satoshi akabane@logical-paradox.org
 * @version $Id: JDBM_IndexAccessor.java,v 1.1 2004/07/22 16:16:48 rampil Exp $
 */
public class JDBM_IndexAccessor implements IndexAccessor {
	private JDBMRecordManager jdbm;
	private JDBMHashtable table;
	private boolean closed;

	public JDBM_IndexAccessor( String filename ) throws IOException {
		jdbm = new JDBMRecordManager( filename );
		table = jdbm.getHashtable( "FTS_INDEX_TBL" );
		closed = false;
	}
	public void close() throws IndexAccessException {
		try {
			if( closed == false && jdbm != null ) {
				table = null;
				jdbm.close();
				jdbm = null;
				closed = true;
			}
		} catch( IOException e ) {
			throw new IndexAccessException( e.getMessage() );
		}
	}
	public boolean isClosed() {
		return closed;
	}
	public void addKey( Key k, Object o ) throws IndexAccessException {
		try {
			if( o == null ) {
				throw new IndexAccessException( "NULLでした" );
			}
			table.put( k, o );
		} catch( IOException e ) {
			e.printStackTrace();
			throw new IndexAccessException( e.getMessage() );
		}
	}
	public Object removeKey( Key k ) throws IndexAccessException {
		try {
			Object o = getValue( k );
			table.remove( k );
			return o;
		} catch( IOException e ) {
			throw new IndexAccessException( e.getMessage() );
		}
	}
	public Object getValue( Key k ) throws IndexAccessException {
		try {
			return table.get( k );
		} catch( IOException e ) {
			throw new IndexAccessException( e.getMessage() );
		}
	}
	public Enumeration keys() throws IndexAccessException {
		try {
			return new JDBM_IndexAccessorEnumeration( table.keys() );
		} catch( IOException e ) {
			throw new IndexAccessException( e.getMessage() );
		}
	}
	public Enumeration values() throws IndexAccessException {
		try {
			return new JDBM_IndexAccessorEnumeration( table.values() );
		} catch( IOException e ) {
			throw new IndexAccessException( e.getMessage() );
		}
	}

	class JDBM_IndexAccessorEnumeration implements Enumeration {
		private final JDBMEnumeration _e;
		public JDBM_IndexAccessorEnumeration( JDBMEnumeration e ) {
			_e = e;
		}
		public boolean hasMoreElements() {
			boolean rc = false;
			try {
				rc = _e.hasMoreElements();
			} catch( IOException e ) {
				rc = false;					// 例外が発生したら，もうないものとして返す
			}

			return rc;
		}
		public Object nextElement() throws NoSuchElementException {
			try {
				return _e.nextElement();
			} catch( IOException e ) {
				throw new NoSuchElementException( e.getMessage() );
			}
		}
	}
}
