package com.hithomelabs.princeton1.module4;

import java.util.Iterator;

import javax.annotation.Nonnull;

public class ArrayQueue<E> extends Queue<E>{

    private E[] queueArray = (E[]) new Object[1];
    private int startPtr = 0;
    private int endPtr = 0;

    @Override
    public boolean isEmpty() {
        return startPtr >= endPtr;
    }

    @Override
    public E dequeue() {
        if(isEmpty()){
            return null;
        }
        E currentValue = queueArray[startPtr];
        queueArray[startPtr++] = null;
        if(size() < queueArray.length/4){
            changeArraySize(queueArray.length/2);
        }
        return currentValue;
    }

    @Override
    public void enqueue(E element) {
        queueArray[endPtr++] = element;
        if(endPtr >= queueArray.length){
            changeArraySize(queueArray.length*2);
        }
    }

    @Override
    public int size() {
        return endPtr - startPtr;
    }

    private void changeArraySize(int targetSize){
        E[] tempArray = queueArray;
        int oldArraySize = tempArray.length;
        queueArray = (E[]) new Object[targetSize];
        int j = 0;
        for(int i=startPtr; i<endPtr; i++)
            queueArray[j++]=tempArray[i];
        endPtr = size();
        startPtr = 0;
    }

    @Nonnull
    @Override
    public Iterator<E> iterator() {
        return new QueueArrayIterator();
    }

    private class QueueArrayIterator implements Iterator<E>{

        private int iteratorIndex = startPtr;

        @Override
        public boolean hasNext() {
            return iteratorIndex<endPtr;
        }

        @Override
        public E next() {
            return queueArray[iteratorIndex++];
        }
    }
}
