/*
 * 
 * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * The contents of this file are subject to the Sun Community Source
 * License v3.0/Jini Technology Specific Attachment v 1.0 (the
 * "License"). You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://wwws.sun.com/software/jini/licensing/SCSL3_JiniTSA1.html.
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Reference Code is Jini Technology Core Platform code, v2.0. The
 * Developer of the Reference Code is Sun Microsystems, Inc.
 * 
 * Contributor(s): Sun Microsystems, Inc.
 * 
 * The contents of this file comply with the Jini Technology Core
 * Platform Compatibility Kit, v2.0A.
 * 
 * Tester(s): Sun Microsystems, Inc.
 * 
 * Test Platform(s):
 * Java 2 SDK, Standard Edition, Version 1.4.2_03 for Solaris(TM)SPARC/x86
 * Java 2 SDK, Standard Edition, Version 1.4.2_03 for Linux (Intel x86)
 * Java 2 SDK, Standard Edition, Version 1.4.2_03 for Windows (Intel Platform)
 * 
 */
package com.sun.jini.outrigger;

import java.rmi.RemoteException;
import net.jini.core.entry.Entry;
import net.jini.core.entry.UnusableEntryException;
import net.jini.id.Uuid;

/**
 * The iterator that is returned to the client.
 * <code>IteratorProxy</code> uses a <code>RemoteIter</code> reference
 * to talk to the server.  The <code>RemoteIter</code> object is its
 * partner on the server side.
 * <p>
 * Note, because there is no way to duplicate one of these objects, or
 * get a new reference to the underlying iteration one (a situation
 * that is unlikely to change since part of the iteration is local), we
 * don't need to do anything special for equality. The default
 * implementations of <code>equals</code> and <code>hashCode</code>
 * work fine.
 */
class IteratorProxy implements AdminIterator {
    /**
     * The <code>Uuid</code> of the iteration this 
     * proxy is associated with.
     */
    private final Uuid iterationUuid;

    /** 
     * Reference to the server.
     * Only assigned by this class.
     */
    OutriggerAdmin server;

    /** Last set of reps we got from the server */
    private EntryRep[] reps;

    /** 
     * Index of the next entry in rep to return.  If <code>delete()</code>
     * we will call <code>iter.delete()</code> next - 1
     */
    private int next = -1;	

    /**
     * How many entries to ask for each time we go to the server
     */
    private final int fetchSize;

    /** ID of last entry we got from server */
    private Uuid lastId = null;
    
    /**
     * Create client side iterator proxy.
     * @param iterationUuid The identity of the iteration this proxy is for.
     * @param server reference to remote server for the space.
     * @param fetchSize Number of entries to ask for when it goes to the
     *                  server
     * @throws NullPointerException if <code>server</code> or
     *         <code>iterationUuid</code> is <code>null</code>.     
     */
    IteratorProxy(Uuid iterationUuid, OutriggerAdmin server, int fetchSize) {
	if (iterationUuid == null)
	    throw new NullPointerException("iterationUuid must be non-null");

	if (server == null)
	    throw new NullPointerException("server must be non-null");
       
	if (fetchSize <= 0 && fetchSize != JavaSpaceAdmin.USE_DEFAULT)
	    throw new IllegalArgumentException
		("fetchSize must be postive or JavaSpaceAdmin.USE_DEFAULT");

	this.iterationUuid = iterationUuid;
	this.server = server;
	this.fetchSize = fetchSize;
    }

    // purposefully inherit doc comment from supertype
    public Entry next() throws UnusableEntryException, RemoteException {
	assertOpen();
	
	if (next < 0 || next >= reps.length) {
	    // Need to get more Entries
	    reps = server.nextReps(iterationUuid, fetchSize, lastId);
	    
	    if (reps == null) {
		// Finished
		close();
		return null;
	    }		
	    
	    lastId = reps[reps.length-1].id();
	    
	    next = 0;
	}
	
	// This may throw UnusableEntryException, but that's
	// the right thing
	return reps[next++].entry();
    }

    // purposefully inherit doc comment from supertype
    public void delete() throws RemoteException {
	if (next < 0) 
	    throw new IllegalStateException("AdminIterator:Can't call " +
					    "delete before calling next()");

	assertOpen();
	server.delete(iterationUuid, reps[next-1].id());
    }
    
    // purposefully inherit doc comment from supertype
    public void close() throws RemoteException {
	if (server != null) {
	    // always set to null, and then try to use the remote method,
	    // which is actually optional
	    OutriggerAdmin it = server;
	    server = null;
	    reps = null;
	    it.close(iterationUuid);
	}
    }

    /**
     * Throw <code>IllegalStateException</code> if this iterator
     * has been closed; otherwise just return.
     */
    private void assertOpen() throws IllegalStateException {
	if (server == null) {
	    throw new IllegalStateException("closed AdminIterator");
	}
    }

    public String toString() {
	return getClass().getName() + " for " + iterationUuid + 
	    " (through " + server + ")";
    }
}
