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.LazyByteIterable;
import org.eclipse.collections.api.RichIterable;
import org.eclipse.collections.api.bag.Bag;
import org.eclipse.collections.api.bag.primitive.LongBag;
import org.eclipse.collections.api.block.function.primitive.LongToObjectFunction;
import org.eclipse.collections.api.block.function.primitive.ObjectLongToObjectFunction;
import org.eclipse.collections.api.block.predicate.primitive.LongPredicate;
import org.eclipse.collections.api.block.predicate.primitive.ByteLongPredicate;
import org.eclipse.collections.api.block.procedure.Procedure;
import org.eclipse.collections.api.block.procedure.primitive.LongProcedure;
import org.eclipse.collections.api.block.procedure.primitive.ByteLongProcedure;
import org.eclipse.collections.api.block.procedure.primitive.ByteProcedure;
import org.eclipse.collections.api.collection.primitive.MutableLongCollection;
import org.eclipse.collections.api.iterator.LongIterator;
import org.eclipse.collections.api.iterator.MutableLongIterator;
import org.eclipse.collections.api.iterator.ByteIterator;
import org.eclipse.collections.api.map.primitive.LongByteMap;
import org.eclipse.collections.api.map.primitive.ImmutableByteLongMap;
import org.eclipse.collections.api.map.primitive.ByteLongMap;
import org.eclipse.collections.api.set.primitive.MutableByteSet;
import org.eclipse.collections.api.tuple.primitive.ByteLongPair;
import org.eclipse.collections.impl.lazy.AbstractLazyIterable;
import org.eclipse.collections.impl.lazy.primitive.AbstractLazyByteIterable;
import org.eclipse.collections.impl.primitive.AbstractLongIterable;
import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples;

abstract class BaseByteLongMap extends AbstractLongIterable implements ByteLongMap {
    static final long KEY_MASK = -1L >>> (64 - (Byte.BYTES * 8));
    static final long VALUE_MASK = -1L >>> (64 - (Long.BYTES * 8));

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

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

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

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

    protected abstract MapStoreCursor iterationCursor();

    protected abstract MapStoreCursor keyCursor(byte key);

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

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

    @Override
    public long getOrThrow(byte 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(byte key) {
        try (MapStoreCursor cursor = keyCursor(key)) {
            return cursor.elementFound();
        }
    }

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

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

    @Override
    public LazyByteIterable keysView() {
        return new AbstractLazyByteIterable() {
            @Override
            public ByteIterator byteIterator() {
                return new KeyIterator(iterationCursor());
            }

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

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

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

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

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

    @Override
    public MutableLongIterator longIterator() {
        return new ValueIterator(iterationCursor());
    }

    @Override
    public long[] toArray() {
        long[] data = new long[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 long detectIfNone(LongPredicate predicate, long ifNone) {
        try (MapStoreCursor cursor = iterationCursor()) {
            while (cursor.next()) {
                long value = fromValue(cursor.getValue());
                if (predicate.accept(value)) {
                    return value;
                }
            }
        }
        return ifNone;
    }

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

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

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

    @Override
    public <T> T injectInto(T injectedValue, ObjectLongToObjectFunction<? 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 long max() {
        try (MapStoreCursor cursor = iterationCursor()) {
            if (!cursor.next()) { throw new NoSuchElementException(); }
            long max = fromValue(cursor.getValue());
            while (cursor.next()) {
                max = (long) Math.max(max, fromValue(cursor.getValue()));
            }
            return max;
        }
    }

    @Override
    public long min() {
        try (MapStoreCursor cursor = iterationCursor()) {
            if (!cursor.next()) { throw new NoSuchElementException(); }
            long min = fromValue(cursor.getValue());
            while (cursor.next()) {
                min = (long) 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 long get(byte key) {
        return getIfAbsent(key, (long) 0);
    }

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

    @Override
    public ByteLongMap select(ByteLongPredicate predicate) {
        throw new UnsupportedOperationException("ByteLongBufferMap.select not implemented yet");
    }

    @Override
    public ByteLongMap reject(ByteLongPredicate predicate) {
        throw new UnsupportedOperationException("ByteLongBufferMap.reject not implemented yet");
    }

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

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

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

    @Override
    public LongBag select(LongPredicate predicate) {
        throw new UnsupportedOperationException("ByteLongBufferMap.select not implemented yet");
    }

    @Override
    public LongBag reject(LongPredicate predicate) {
        throw new UnsupportedOperationException("ByteLongBufferMap.reject not implemented yet");
    }

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

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

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

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

    @Override
    public boolean noneSatisfy(LongPredicate 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 ByteIterator { KeyIterator(MapStoreCursor cursor) { super(cursor); } @Override public byte next() { next0(); return fromKey(cursor.getKey()); } } private static class KeyValueIterator extends BaseIterator implements Iterator<ByteLongPair> { KeyValueIterator(MapStoreCursor cursor) { super(cursor); } @Override public ByteLongPair next() { next0(); return PrimitiveTuples.pair(fromKey(cursor.getKey()), fromValue(cursor.getValue())); } } protected static class ValueIterator extends BaseIterator implements LongIterator, MutableLongIterator { ValueIterator(MapStoreCursor cursor) { super(cursor); } @Override public long next() { next0(); return fromValue(cursor.getValue()); } @Override public void remove() { throw new UnsupportedOperationException("ValueIterator.remove not implemented yet"); } } }