package queue;

/**
 * @author Doschennikov Nikita (me@fymio.us)
 */
public class ArrayQueue extends AbstractQueue {

    private Object[] queue;
    private int head;

    public ArrayQueue() {
        queue = new Object[4];
        head = 0;
    }

    @Override
    public void enqueue(Object element) {
        assert element != null : "Element must not be null";
        ensureCapacity();
        queue[(head + size) % queue.length] = element;
        size++;
    }

    @Override
    public void push(Object element) {
        assert element != null : "Element must not be null";
        ensureCapacity();
        head = (head - 1 + queue.length) % queue.length;
        queue[head] = element;
        size++;
    }

    @Override
    public Object element() {
        assert size > 0 : "Queue is empty";
        return queue[head];
    }

    @Override
    public Object peek() {
        assert size > 0 : "Queue is empty";
        return queue[(head + size - 1) % queue.length];
    }

    @Override
    public Object dequeue() {
        assert size > 0 : "Queue is empty";
        Object result = queue[head];
        queue[head] = null;
        head = (head + 1) % queue.length;
        size--;
        return result;
    }

    @Override
    public Object remove() {
        assert size > 0 : "Queue is empty";
        int tail = (head + size - 1) % queue.length;
        Object result = queue[tail];
        queue[tail] = null;
        size--;
        return result;
    }

    @Override
    protected Object get(int i) {
        return queue[(head + i) % queue.length];
    }

    @Override
    protected void clearImpl() {
        queue = new Object[4];
        head = 0;
    }

    @Override
    protected AbstractQueue createEmpty() {
        return new ArrayQueue();
    }

    private void ensureCapacity() {
        if (size < queue.length) return;
        Object[] newQueue = new Object[queue.length * 2];
        for (int i = 0; i < size; i++) {
            newQueue[i] = queue[(head + i) % queue.length];
        }
        queue = newQueue;
        head = 0;
    }
}
