package at.yawk.numaec;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.collections.api.LazyIntIterable;
import org.eclipse.collections.api.RichIterable;
import org.eclipse.collections.api.bag.Bag;
import org.eclipse.collections.api.bag.primitive.ShortBag;
import org.eclipse.collections.api.block.function.primitive.ShortToObjectFunction;
import org.eclipse.collections.api.block.function.primitive.ObjectShortToObjectFunction;
import org.eclipse.collections.api.block.predicate.primitive.ShortPredicate;
import org.eclipse.collections.api.block.predicate.primitive.IntShortPredicate;
import org.eclipse.collections.api.block.procedure.Procedure;
import org.eclipse.collections.api.block.procedure.primitive.ShortProcedure;
import org.eclipse.collections.api.block.procedure.primitive.IntShortProcedure;
import org.eclipse.collections.api.block.procedure.primitive.IntProcedure;
import org.eclipse.collections.api.collection.primitive.MutableShortCollection;
import org.eclipse.collections.api.iterator.ShortIterator;
import org.eclipse.collections.api.iterator.MutableShortIterator;
import org.eclipse.collections.api.iterator.IntIterator;
import org.eclipse.collections.api.map.primitive.ShortIntMap;
import org.eclipse.collections.api.map.primitive.ImmutableIntShortMap;
import org.eclipse.collections.api.map.primitive.IntShortMap;
import org.eclipse.collections.api.set.primitive.MutableIntSet;
import org.eclipse.collections.api.tuple.primitive.IntShortPair;
import org.eclipse.collections.impl.lazy.AbstractLazyIterable;
import org.eclipse.collections.impl.lazy.primitive.AbstractLazyIntIterable;
import org.eclipse.collections.impl.primitive.AbstractShortIterable;
import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples;

abstract class BaseIntShortMap extends AbstractShortIterable implements IntShortMap {
    static final long KEY_MASK = -1L >>> (64 - (Integer.BYTES * 8));
    static final long VALUE_MASK = -1L >>> (64 - (Short.BYTES * 8));

    static long toKey(int key) {
        return key & KEY_MASK;
    }

    static long toValue(short value) {
        return value & VALUE_MASK;
    }

    @SuppressWarnings("ConstantConditions")
    static int fromKey(long key) {
        if (KEY_MASK != -1) { if (key < 0 || key > KEY_MASK) { throw new IllegalArgumentException(); } }
        return (int) key;
    }

    @SuppressWarnings("ConstantConditions")
    static short fromValue(long value) {
        if (VALUE_MASK != -1) { if (value < 0 || value > VALUE_MASK) { throw new IllegalArgumentException(); } }
        return (short) value;
    }

    protected abstract MapStoreCursor iterationCursor();

    protected abstract MapStoreCursor keyCursor(int key);

    @DoNotMutate
    void checkInvariants() {
        int count = count(x -> true);
        if (count != size()) { throw new AssertionError(); }
    }

    @Override
    public short getIfAbsent(int key, short ifAbsent) {
        try (MapStoreCursor cursor = keyCursor(key)) {
            if (cursor.elementFound()) {
                return fromValue(cursor.getValue());
            } else {
                return ifAbsent;
            }
        }
    }

    @Override
    public short getOrThrow(int key) {
        try (MapStoreCursor cursor = keyCursor(key)) {
            if (cursor.elementFound()) {
                return fromValue(cursor.getValue());
            } else {
                throw new IllegalStateException("Key " + key + " not present");
            }
        }
    }

    @Override
    public boolean containsKey(int key) {
        try (MapStoreCursor cursor = keyCursor(key)) {
            return cursor.elementFound();
        }
    }

    @Override
    public void forEachKey(IntProcedure procedure) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                procedure.value(fromKey(cursor.getKey()));
            }
        }
    }

    @Override
    public void forEachKeyValue(IntShortProcedure procedure) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                procedure.value(fromKey(cursor.getKey()),
                                fromValue(cursor.getValue()));
            }
        }
    }

    @Override
    public LazyIntIterable keysView() {
        return new AbstractLazyIntIterable() {
            @Override
            public IntIterator intIterator() {
                return new KeyIterator(iterationCursor());
            }

            @Override
            public void each(IntProcedure procedure) {
                forEachKey(procedure);
            }
        };
    }

    @Override
    public RichIterable<IntShortPair> keyValuesView() {
        return new AbstractLazyIterable<IntShortPair>() {
            @Override
            public Iterator<IntShortPair> iterator() {
                return new KeyValueIterator(iterationCursor());
            }

            @Override
            public void each(Procedure<? super IntShortPair> procedure) {
                iterator().forEachRemaining(procedure);
            }
        };
    }

    @Override
    public boolean containsValue(short value) {
        long needle = toValue(value);
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                if (cursor.getValue() == needle) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void forEachValue(ShortProcedure procedure) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                procedure.value(fromValue(cursor.getValue()));
            }
        }
    }

    @Override
    public MutableShortIterator shortIterator() {
        return new ValueIterator(iterationCursor());
    }

    @Override
    public short[] toArray() {
        short[] data = new short[size()];
        try (MapStoreCursor cursor = iterationCursor()) {
            int i = 0;
            while (cursor.next()) {
                if (i >= data.length) { throw new ConcurrentModificationException(); }
                data[i++] = fromValue(cursor.getValue());
            }
            if (i < data.length) { throw new ConcurrentModificationException(); }
            return data;
        }
    }

    @Override
    public short detectIfNone(ShortPredicate predicate, short ifNone) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                short value = fromValue(cursor.getValue());
                if (predicate.accept(value)) {
                    return value;
                }
            }
        }
        return ifNone;
    }

    @Override
    public int count(ShortPredicate predicate) {
        int count = 0;
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                short value = fromValue(cursor.getValue());
                if (predicate.accept(value)) {
                    count++;
                }
            }
        }
        return count;
    }

    @Override
    public boolean anySatisfy(ShortPredicate predicate) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                short value = fromValue(cursor.getValue());
                if (predicate.accept(value)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean allSatisfy(ShortPredicate predicate) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                short value = fromValue(cursor.getValue());
                if (!predicate.accept(value)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public <T> T injectInto(T injectedValue, ObjectShortToObjectFunction<? super T, ? extends T> function) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                injectedValue = function.valueOf(injectedValue, fromValue(cursor.getValue()));
            }
        }
        return injectedValue;
    }

    @Override
    public long
 sum() {
        long
 sum = 0;
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                sum += fromValue(cursor.getValue());
            }
        }
        return sum;
    }

    @Override
    public short max() {
        try (MapStoreCursor cursor = iterationCursor()) {
            if (!cursor.next()) { throw new NoSuchElementException(); }
            short max = fromValue(cursor.getValue());
            while (cursor.next()) {
                max = (short) Math.max(max, fromValue(cursor.getValue()));
            }
            return max;
        }
    }

    @Override
    public short min() {
        try (MapStoreCursor cursor = iterationCursor()) {
            if (!cursor.next()) { throw new NoSuchElementException(); }
            short min = fromValue(cursor.getValue());
            while (cursor.next()) {
                min = (short) Math.min(min, fromValue(cursor.getValue()));
            }
            return min;
        }
    }

    @Override
    public void appendString(Appendable appendable, String start, String separator, String end) {
        try (MapStoreCursor cursor = iterationCursor()) {
            appendable.append(start);
            boolean first = true;
            while (cursor.next()) {
                if (first) {
                    first = false;
                } else {
                    appendable.append(separator);
                }
                appendable.append(String.valueOf(fromValue(cursor.getValue())));
            }
            appendable.append(end);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("{");
        try (MapStoreCursor cursor = iterationCursor()) {
            boolean first = true;
            while (cursor.next()) {
                if (first) {
                    first = false;
                } else {
                    builder.append(", ");
                }
                builder.append(fromKey(cursor.getKey()))
                        .append('=')
                        .append(fromValue(cursor.getValue()));
            }
            return builder.append('}').toString();
        }
    }

    @Override
    public short get(int key) {
        return getIfAbsent(key, (short) 0);
    }

    @Override
    public ShortIntMap flipUniqueValues() {
        throw new UnsupportedOperationException("IntShortBufferMap.flipUniqueValues not implemented yet");
    }

    @Override
    public IntShortMap select(IntShortPredicate predicate) {
        throw new UnsupportedOperationException("IntShortBufferMap.select not implemented yet");
    }

    @Override
    public IntShortMap reject(IntShortPredicate predicate) {
        throw new UnsupportedOperationException("IntShortBufferMap.reject not implemented yet");
    }

    @Override
    public ImmutableIntShortMap toImmutable() {
        throw new UnsupportedOperationException("IntShortBufferMap.toImmutable not implemented yet");
    }

    @Override
    public MutableIntSet keySet() {
        throw new UnsupportedOperationException("IntShortBufferMap.keySet not implemented yet");
    }

    @Override
    public MutableShortCollection values() {
        throw new UnsupportedOperationException("IntShortBufferMap.values not implemented yet");
    }

    @Override
    public ShortBag select(ShortPredicate predicate) {
        throw new UnsupportedOperationException("IntShortBufferMap.select not implemented yet");
    }

    @Override
    public ShortBag reject(ShortPredicate predicate) {
        throw new UnsupportedOperationException("IntShortBufferMap.reject not implemented yet");
    }

    @Override
    public <V> Bag<V> collect(ShortToObjectFunction<? extends V> function) {
        throw new UnsupportedOperationException("IntShortBufferMap.collect not implemented yet");
    }

    @Override
    public boolean contains(short value) {
        return containsValue(value);
    }

    @Override
    public void forEach(ShortProcedure procedure) {
        forEachValue(procedure);
    }

    @Override
    public void each(ShortProcedure procedure) {
        forEachValue(procedure);
    }

    @Override
    public boolean noneSatisfy(ShortPredicate predicate) {
        return !anySatisfy(predicate);
    }

    private static abstract class BaseIterator {
        
this cursor is never closed, but since all MapStoreCursor.close() does is make it available for reuse, that's not too bad.
/** * this cursor is never closed, but since all {@link MapStoreCursor#close()} does is make it available for * reuse, that's not too bad. */
protected final MapStoreCursor cursor; private boolean peeked; BaseIterator(MapStoreCursor cursor) { this.cursor = cursor; } protected void next0() { if (!hasNext()) { throw new NoSuchElementException(); } peeked = false; } public boolean hasNext() { if (peeked) { return true; } else { return peeked = cursor.next(); } } } private static class KeyIterator extends BaseIterator implements IntIterator { KeyIterator(MapStoreCursor cursor) { super(cursor); } @Override public int next() { next0(); return fromKey(cursor.getKey()); } } private static class KeyValueIterator extends BaseIterator implements Iterator<IntShortPair> { KeyValueIterator(MapStoreCursor cursor) { super(cursor); } @Override public IntShortPair next() { next0(); return PrimitiveTuples.pair(fromKey(cursor.getKey()), fromValue(cursor.getValue())); } } protected static class ValueIterator extends BaseIterator implements ShortIterator, MutableShortIterator { ValueIterator(MapStoreCursor cursor) { super(cursor); } @Override public short next() { next0(); return fromValue(cursor.getValue()); } @Override public void remove() { throw new UnsupportedOperationException("ValueIterator.remove not implemented yet"); } } }