/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.server.userimport.oucsir;

import java.util.Iterator;

import org.apache.log4j.Logger;

/**
 * Wrapper that attempts to validate objects comming out of an iterator.
 * If an object does't validate get another one until we have a "good" object.
 * @author buckett
 */
class ValidatingIterator implements Iterator
{
    private final static Logger log = Logger.getLogger(ValidatingIterator.class);
    
    private Validator nextValid;
    private Iterator iterator;
    
    public ValidatingIterator(Iterator iterator)
    {
        this.iterator = iterator;
    }

    public boolean hasNext()
    {
        loadNext();
        return nextValid != null;
    }

    public Object next()
    {
        loadNext();
        Validator object = nextValid;
        nextValid = null;
        return object;
    }
    
    private void loadNext()
    {
        if (nextValid != null)
            return;
        for(Object next = iterator.next(); next != null; next = iterator.next())
        {
            if (next instanceof Validator)
            {       
                Validator maybeValid = (Validator) next;
                String problems = maybeValid.problems();
                if (problems == null)
                {
                    this.nextValid = maybeValid;
                    return;
                }
                else
                    log.warn("Problems with: "+ maybeValid+ "\n"+ problems);
            }
            else
                log.warn("Doesn't implement Validator: "+ next);
        }
    }

    public void remove()
    {
        throw new UnsupportedOperationException();
    }

}
