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[5];
    private int startPtr;
    private int endPtr;
    private int size;
    private int queueArrayLength = queueArray.length;

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

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

    @Override
    public void enqueue(E element) {
        queueArray[endPtr++ % queueArrayLength] = element;
        size++;
        if(size == queueArrayLength){
            changeArraySize(queueArrayLength*2);
        }
    }

    @Override
    public int size() {
        return size;
    }

    private void changeArraySize(int targetSize){
        E[] tempArray = queueArray;
        int oldArraySize = tempArray.length;
        queueArray = (E[]) new Object[targetSize];
        int j = 0;

        for(int i=0; i<size; i++)
            queueArray[j++]=tempArray[(startPtr+i)%oldArraySize];
        endPtr = size();
        startPtr = 0;
        queueArrayLength = queueArray.length;
    }

    @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 % queueArrayLength < endPtr % queueArrayLength;
        }

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