package org.xbib.datastructures.immutable;

import java.util.Spliterator;
import java.util.Spliterators;

abstract class IteratorBasedImmutableMap<K, V> extends ImmutableMap<K, V> {
    abstract UnmodifiableIterator<Entry<K, V>> entryIterator();

    Spliterator<Entry<K, V>> entrySpliterator() {
        return Spliterators.spliterator(
                entryIterator(),
                size(),
                Spliterator.DISTINCT | Spliterator.NONNULL | Spliterator.IMMUTABLE | Spliterator.ORDERED);
    }

    @Override
    ImmutableSet<K> createKeySet() {
        return new ImmutableMapKeySet<>(this);
    }

    @Override
    ImmutableSet<Entry<K, V>> createEntrySet() {
        class EntrySetImpl extends ImmutableMapEntrySet<K, V> {
            @Override
            ImmutableMap<K, V> map() {
                return IteratorBasedImmutableMap.this;
            }

            @Override
            public UnmodifiableIterator<Entry<K, V>> iterator() {
                return entryIterator();
            }
        }
        return new EntrySetImpl();
    }

    @Override
    ImmutableCollection<V> createValues() {
        return new ImmutableMapValues<>(this);
    }
}
