package at.oefai.aaa.agent.jam;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import at.oefai.aaa.agent.jam.types.Binding;

/**
 * Helps iterate through World Model entries.
 * @author Marc Huber
 * @author Jaeho Lee
 */
class WorldModelRelationIterator implements Serializable {
    private Relation relation;
    private Iterator<WorldModelRelation> bucket;

    /** Constructor with World Model and relation arguments. */
    WorldModelRelationIterator(final WorldModelTable wt, final Relation pRelation) {
        this.relation = pRelation;
        List<WorldModelRelation> list = wt.getRelations(this.relation.getName());
        this.bucket = list.iterator();
    }

    /** Go to the next matching element. */
    WorldModelRelation getNext(final Binding binding) {
        while (this.bucket.hasNext()) {
            WorldModelRelation wr = this.bucket.next();
            if (wr.matchRelation(this.relation, binding)) {
                return wr;
            }
        }
        return null;
    }

    /** Shuffles the rest of the elements into a random order. */
    void shuffleRest() {
        List<WorldModelRelation> l = new LinkedList<WorldModelRelation>();
        while (this.bucket.hasNext()) {
            l.add(this.bucket.next());
        }
        Collections.shuffle(l);
        this.bucket = l.iterator();
    }

}

