/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.collection.iterators;

import java.util.NoSuchElementException;

public abstract class RandomAccessIntIterator implements IntListIterator {
    
    private int index;
    
    private int last;

    protected abstract int size();
    
    protected abstract int get(int index);
    
    protected void remove(int index) {
        throw new UnsupportedOperationException();
    }
    
    protected void add(int index, int value) {
        throw new UnsupportedOperationException();
    }
    
    protected void set(int index, int value) {
        throw new UnsupportedOperationException();
    }
    
    public RandomAccessIntIterator() {
        this(0);
    }

    public RandomAccessIntIterator(int index) {
        this.index = index;
        this.last = -1;
    }

    @Override
    public boolean hasNext() {
        return index < size();
    }

    @Override
    public boolean hasPrevious() {
        return index > 0;
    }

    @Override
    public int nextInt() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return get(last = index++);
    }

    @Override
    public int previousInt() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        return get(last = --index);
    }

    @Override
    public int nextIndex() {
        return index;
    }

    @Override
    public int previousIndex() {
        return index - 1;
    }

    @Override
    public void add(int k) {
        add(index++, k);
    }

    @Override
    public void set(int k) {
        if (last == -1) {
            throw new IllegalStateException();
        }
        set(last, k);
    }

    @Override
    public void remove() {
        if (last == -1) {
            throw new IllegalStateException();
        }
        remove(last);
        // If the last operation was a next(), 
        // we are removing an element *before* us, 
        // and we must decrease pos correspondingly.
        if (last < index) {
            index--;
        }
        last = -1;
    }
    
    
}
