package org.xbib.datastructures.immutable;

import java.util.Comparator;
import java.util.Spliterator;
import org.xbib.datastructures.api.SortedIterable;

/**
 * List returned by {@code ImmutableSortedSet.asList()} when the set isn't empty.
 */
final class ImmutableSortedAsList<E> extends RegularImmutableAsList<E>
        implements SortedIterable<E> {
    ImmutableSortedAsList(ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) {
        super(backingSet, backingList);
    }

    @Override
    ImmutableSortedSet<E> delegateCollection() {
        return (ImmutableSortedSet<E>) super.delegateCollection();
    }

    @Override
    public Comparator<? super E> comparator() {
        return delegateCollection().comparator();
    }

    // Override indexOf() and lastIndexOf() to be O(log N) instead of O(N).

    @Override
    public int indexOf(Object target) {
        int index = delegateCollection().indexOf(target);
        return (index >= 0 && get(index).equals(target)) ? index : -1;
    }

    @Override
    public int lastIndexOf(Object target) {
        return indexOf(target);
    }

    @Override
    public boolean contains(Object target) {
        // Necessary for ISS's with comparators inconsistent with equals.
        return indexOf(target) >= 0;
    }

    @Override
    ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
        ImmutableList<E> parentSubList = super.subListUnchecked(fromIndex, toIndex);
        return new RegularImmutableSortedSet<E>(parentSubList, comparator()).asList();
    }

    @Override
    public Spliterator<E> spliterator() {
        return Spliterators.indexed(
                size(),
                ImmutableList.SPLITERATOR_CHARACTERISTICS | Spliterator.SORTED | Spliterator.DISTINCT,
                delegateList()::get,
                comparator());
    }
}
