/* ======================================================================
   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.io.IOException;
import java.io.Reader;
import java.util.Iterator;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * Base class for converting an XML stream into a stream of java objects.
 */
abstract class XppIterator implements Iterator
{

    protected XmlPullParser xpp;
    
    /**
     * The next user to be returned by the iterator.
     */
    private Object next;
	private boolean errorMessageSent = false;

    public void setReader(Reader source) throws XmlPullParserException
    {
        xpp = XmlPullParserFactory.newInstance().newPullParser();
        xpp.setInput(source);
    }

    /**
     * Isn't implemented.
     * @throws UnsupportedOperationException Isn't implemented.
     */
    public void remove()
    {
        throw new UnsupportedOperationException(XppIterator.class
            .toString()
            + " doesn't support remove.");
    }

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

    public Object next()
    {
        Object toReturn = null;
        if (hasNext())
        {
            toReturn = this.next;
            this.next = null;
        }
        return toReturn;
        
    }
    

    /**
     * Class to remove code duplication. Hopefully compiler will inline.
     */
    public boolean checkTagAndProgress(String name) throws XmlPullParserException, IOException
    {
        if (name.equals(xpp.getName()))
        {
            xpp.next();
            if (xpp.getEventType() == XmlPullParser.TEXT)
                return true;
        }
        return false;                        
    }
    
    
    /**
     * Get string showing where we are in the input.
     */
    public String getXppPosition()
    {
        return "Line: " + xpp.getLineNumber() + " Column: "
            + xpp.getColumnNumber() + " ";
    }
    
    abstract protected Object loadNext();
    
}
