package at.yawk.numaec;

import org.eclipse.collections.api.IntIterable;
import org.eclipse.collections.api.bag.MutableBag;
import org.eclipse.collections.api.bag.primitive.MutableByteBag;
import org.eclipse.collections.api.block.function.primitive.ByteFunction;
import org.eclipse.collections.api.block.function.primitive.ByteFunction0;
import org.eclipse.collections.api.block.function.primitive.ByteToByteFunction;
import org.eclipse.collections.api.block.function.primitive.ByteToObjectFunction;
import org.eclipse.collections.api.block.function.primitive.IntByteToByteFunction;
import org.eclipse.collections.api.block.function.primitive.IntToByteFunction;
import org.eclipse.collections.api.block.predicate.primitive.BytePredicate;
import org.eclipse.collections.api.block.predicate.primitive.IntBytePredicate;
import org.eclipse.collections.api.iterator.MutableByteIterator;
import org.eclipse.collections.api.map.primitive.MutableByteIntMap;
import org.eclipse.collections.api.map.primitive.MutableIntByteMap;
import org.eclipse.collections.api.map.primitive.IntByteMap;

public class IntByteBTreeMap extends BaseIntByteMap implements IntByteBufferMap {
    protected final BTree bTree;
    protected int size = 0;

    IntByteBTreeMap(LargeByteBufferAllocator allocator, BTreeConfig config) {
        int leafSize = Integer.BYTES + Byte.BYTES;
        int branchSize = config.entryMustBeInLeaf ? Integer.BYTES : leafSize;
        this.bTree = new BTree(allocator, config, branchSize, leafSize) {
            @Override
            protected void writeBranchEntry(LargeByteBuffer lbb, long address, long key, long value) {
                lbb.setInt(address, fromKey(key));
                if (!config.entryMustBeInLeaf) {
                    lbb.setByte(address + Integer.BYTES, fromValue(value));
                }
            }

            @Override
            protected void writeLeafEntry(LargeByteBuffer lbb, long address, long key, long value) {
                lbb.setInt(address, fromKey(key));
                lbb.setByte(address + Integer.BYTES, fromValue(value));
            }

            @Override
            protected long readBranchKey(LargeByteBuffer lbb, long address) {
                return toKey(lbb.getInt(address));
            }

            @Override
            protected long readBranchValue(LargeByteBuffer lbb, long address) {
                if (config.entryMustBeInLeaf) {
                    throw new AssertionError();
                } else {
                    return toValue(lbb.getByte(address + Integer.BYTES));
                }
            }

            @Override
            protected long readLeafKey(LargeByteBuffer lbb, long address) {
                return toKey(lbb.getInt(address));
            }

            @Override
            protected long readLeafValue(LargeByteBuffer lbb, long address) {
                return toValue(lbb.getByte(address + Integer.BYTES));
            }
        };
    }

    @Override
    protected MapStoreCursor iterationCursor() {
        BTree.Cursor cursor = bTree.allocateCursor();
        cursor.descendToStart();
        return cursor;
    }

    @Override
    protected MapStoreCursor keyCursor(int key) {
        BTree.Cursor cursor = bTree.allocateCursor();
        cursor.descendToKey(toKey(key));
        return cursor;
    }

    @DoNotMutate
    @Override
    void checkInvariants() {
        super.checkInvariants();
        bTree.checkInvariants();
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void close() {
        bTree.close();
    }

    public static class Mutable extends IntByteBTreeMap implements MutableIntByteBufferMap {
        Mutable(LargeByteBufferAllocator allocator, BTreeConfig config) {
            super(allocator, config);
        }

        @Override
        public void put(int key, byte value) {
            long k = toKey(key);
            long v = toValue(value);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    cursor.setValue(v);
                } else {
                    cursor.simpleInsert(k, v);
                    cursor.balance();
                    size++;
                }
            }
        }

        @Override
        public void putAll(IntByteMap map) {
            map.forEachKeyValue(this::put);
        }

        @Override
        public void updateValues(IntByteToByteFunction function) {
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToStart();
                while (cursor.next()) {
                    byte updated = function.valueOf(fromKey(cursor.getKey()), fromValue(cursor.getValue()));
                    cursor.setValue(toValue(updated));
                }
            }
        }

        @Override
        public void removeKey(int key) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    cursor.simpleRemove();
                    cursor.balance();
                    size--;
                }
            }
        }

        @Override
        public void remove(int key) {
            removeKey(key);
        }

        @Override
        public byte removeKeyIfAbsent(int key, byte value) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    byte v = fromValue(cursor.getValue());
                    cursor.simpleRemove();
                    cursor.balance();
                    size--;
                    return v;
                } else {
                    return value;
                }
            }
        }

        @Override
        public byte getIfAbsentPut(int key, byte value) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    return fromValue(cursor.getValue());
                } else {
                    cursor.simpleInsert(k, toValue(value));
                    cursor.balance();
                    size++;
                    return value;
                }
            }
        }

        @Override
        public byte getIfAbsentPut(int key, ByteFunction0 function) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    return fromValue(cursor.getValue());
                } else {
                    byte v = function.value();
                    cursor.simpleInsert(k, toValue(v));
                    cursor.balance();
                    size++;
                    return v;
                }
            }
        }

        @Override
        public byte getIfAbsentPutWithKey(int key, IntToByteFunction function) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    return fromValue(cursor.getValue());
                } else {
                    byte v = function.valueOf(key);
                    cursor.simpleInsert(k, toValue(v));
                    cursor.balance();
                    size++;
                    return v;
                }
            }
        }

        @Override
        public <P> byte getIfAbsentPutWith(int key, ByteFunction<? super P> function, P parameter) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    return fromValue(cursor.getValue());
                } else {
                    byte v = function.byteValueOf(parameter);
                    cursor.simpleInsert(k, toValue(v));
                    cursor.balance();
                    size++;
                    return v;
                }
            }
        }

        @Override
        public byte updateValue(int key, byte initialValueIfAbsent, ByteToByteFunction function) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    byte updated = function.valueOf(fromValue(cursor.getValue()));
                    cursor.setValue(toValue(updated));
                    return updated;
                } else {
                    byte updated = function.valueOf(initialValueIfAbsent);
                    cursor.simpleInsert(k, toValue(updated));
                    cursor.balance();
                    size++;
                    return updated;
                }
            }
        }

        @Override
        public MutableIntByteMap withKeyValue(int key, byte value) {
            put(key, value);
            return this;
        }

        @Override
        public MutableIntByteMap withoutKey(int key) {
            removeKey(key);
            return this;
        }

        @Override
        public MutableIntByteMap withoutAllKeys(IntIterable keys) {
            keys.forEach(this::removeKey);
            return this;
        }

        @Override
        public MutableIntByteMap asUnmodifiable() {
            throw new UnsupportedOperationException("Mutable.asUnmodifiable not implemented yet");
        }

        @Override
        public MutableIntByteMap asSynchronized() {
            throw new UnsupportedOperationException("Mutable.asSynchronized not implemented yet");
        }

        @Override
        public byte addToValue(int key, byte toBeAdded) {
            long k = toKey(key);
            try (BTree.Cursor cursor = bTree.allocateCursor()) {
                cursor.descendToKey(k);
                if (cursor.elementFound()) {
                    byte updated = (byte) (fromValue(cursor.getValue()) + toBeAdded);
                    cursor.setValue(toValue(updated));
                    return updated;
                } else {
                    cursor.simpleInsert(k, toValue(toBeAdded));
                    cursor.balance();
                    size++;
                    return toBeAdded;
                }
            }
        }

        @Override
        public void clear() {
            bTree.clear();
            size = 0;
        }

        @Override
        public MutableByteIntMap flipUniqueValues() {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.flipUniqueValues not implemented yet");
        }

        @Override
        public MutableIntByteMap select(IntBytePredicate predicate) {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.select not implemented yet");
        }

        @Override
        public MutableByteBag select(BytePredicate predicate) {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.select not implemented yet");
        }

        @Override
        public MutableIntByteMap reject(IntBytePredicate predicate) {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.reject not implemented yet");
        }

        @Override
        public MutableByteBag reject(BytePredicate predicate) {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.reject not implemented yet");
        }

        @Override
        public <V> MutableBag<V> collect(ByteToObjectFunction<? extends V> function) {
            throw new UnsupportedOperationException("IntByteBufferMap.Mutable.collect not implemented yet");
        }

        @Override
        public MutableByteIterator byteIterator() {
            return super.byteIterator();
        }
    }
}