package net.ranides.assira.collection.lists;

import net.ranides.assira.collection.iterators.RandomAccessIterator;

import java.util.*;

/**
 * Trivial implementation of list which does not support any modifications.
 *
 * @param <T> T
 */
public class ImmutableList<T> extends AbstractList<T> {

    private final Object[] items;

    /**
     * Creates new list with elements copied from provided collection
     * @param collection collection
     */
    public ImmutableList(Collection<? extends T> collection) {
        this.items = collection.toArray();
    }

    /**
     * Creates new list with elements copied from provided array
     * @param collection collection
     */
    public ImmutableList(T[] collection) {
        this.items = collection.clone();
    }

    @SuppressWarnings("unchecked")
    @Override
    public T get(int index) {
        return (T)items[index];
    }

    @Override
    public int size() {
        return items.length;
    }

    @Override
    public void sort(Comparator<? super T> c) {
        throw new UnsupportedOperationException("ImmutableList");
    }

    @Override
    public Iterator<T> iterator() {
        return new ForwadItr();
    }

    @Override
    public ListIterator<T> listIterator() {
        return new RandomItr(0);
    }

    @Override
    public ListIterator<T> listIterator(int index) {
        return new RandomItr(index);
    }

    private class RandomItr extends RandomAccessIterator<T> {

        public RandomItr(int index) {
            super(index);
        }

        @Override
        protected int size() {
            return items.length;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected T get(int index) {
            return (T)items[index];
        }
    }

    private class ForwadItr implements Iterator<T> {

        private int index;

        @Override
        public boolean hasNext() {
            return index < items.length;
        }

        @SuppressWarnings("unchecked")
        @Override
        public T next() {
            return (T)items[index++];
        }
    }

}
